[JS] 자바스크립트 코드 트릭
1. 구조 분해 할당을 이용한 변수 swap
let a =5, b =10;
[a,b] = [b,a];
console.log(a,b) // 10,5
2. 배열 생성으로 루프 제거하기
Before
let sum = 0;
for(let i = 5; i< 10; i++){
sum += i;
}
After : 함수형 프로그래밍
const sum = Array.from({length: 5}, (each,i) => i+5 ).reduce((acc,each) => acc + each );
// {length: 5} 대신 new Array(5)가 들어가도 된다
console.log(sum);
3. 배열 내 같은 요소 제거하기
Set 사용
const names = ['Amy','Carol','Lala','David','Lala'];
const uniqueNamesWithArrayFrom = Array.from(new Set(names)); set구조
const uniqueNamesWithSpred = [...new Set(names)];//['Amy','Carol','Lala','David'] set을 배열로
4. Spread 연산자를 이용한 객체 병합
두 객체를 spread 연산자로 별도의 객체에 합칠 수 있다.
const math = {
teacher: 'kim',
mathScore: 100
}
const science = {
teacher: 'choi',
scienceScore: 89
}
const test = {...math,...science};
console.log(test);
/* 같은 키의 경우 teacher 우선 순위에 따라 정해진다. 후자가 우선 순위 높아
{
mathScore: 100,
scienceScore: 89,
teacher: "choi"
}*/
5. &&, || 활용
조건문 외에도 아래처럼 사용 가능하다.
5-1. || 으로 기본값 세팅
const name = inputName || 'SHIN';
inputName 값이 0, undefined, 빈 문자영, null일 경우 기본값 ‘SHIN’이 할당된다.
5.2 && true 실행
true면 실행 하는 조건문
inputName && sayName();
inputName이 true인 경우에만 sayName()을 실행한다.
객체 병합에 활용
const test = (result) => {
return {
name: 'SHIN',
math: 80,
...result && { pass: 'pass'}
}
}
console.log(test(true));// 이 때만 병합
console.log(test(false));
6. 구조 분해 할당 사용
필요한 것만 꺼내 쓰기
const test = {
math: 90,
science: 70,
english: 100,
korean: 50
}
const { math, science } = test;// test 객체중 math, science만 담긴 배열 만듬
객체 생성시 키 생략
변수이름과 프로퍼티 키 일치하는 경우 프로퍼티 키 생략가능
const math = 90;
const science = 80;
const test = {
math, science
}
7. 비구조화 할당 사용하기
함수에 객체를 넘길 경우 필요한 것만 꺼내 쓸 수 있다.
const test = {
math: 90,
science: 70,
english: 100,
korean: 50
}
const language = ({korean,english}) =>{
return{
korean,english
}
}
console.log(language(test));
8. 동적 속성 이름
객체의 키를 동적으로 생성할 수 있다. 키 이름 조작 가능
const subject1 = 'math';
const subject2 = 'english';
const level = '-very hard'
const test = {
[ subject1 + level ]: 100,
[ subject2 ]: 80
}
console.log(test);
/*
{
english: 80,
math-very hard: 100
}
*/
9. !! 연산자를 사용해 Boolean 값으로 바꾸기
!! 연산자를 이용해 0, null, undefined, NaN, 빈 문자열을 false로 그 외엔 true로 변경
const input = null;
const check = (input) => {
if(!!input){
console.log('값이 존재하면 true')
}else{
console.log('값이 존재하지 않으면 false')
}
}
check(input) //값이 존재하지 않으면 false
⚠ 주의 : ! VS !!
!의 경우 0, null, undefined, NaN, 빈 문자열을 true로 반환
const input = null;
const check2 = (input) => {
if(!input){
console.log('값이 존재하지 않으면 true')
}else{
console.log('값이 존재하면 false')
}
}
check2(input) //값이 존재하지 않으면 true
댓글남기기