ES6의 구조 분해 할당 문법을 사용하여 두 변수를 swap할 수 있습니다.
let a = 5, b =10;
[a,b] = [b,a];
console.log(a,b); // 10 5
보통 단순히 범위 루프를 돌고 싶다면 다음과 같이 코드를 작성합니다.
let sum = 0;
fot(let i = 5; i < 10; i += 1){
sum += i;
}
만약 범위 루프를 함수형 프로그래밍 방식으로 사용하고 싶다면 배열을 생성해서 사용할 수 있습니다.
const sum = Array
.from(new Array(5), (_, k)=> k + 5)
.reduce(acc, cur) => acc + cur, 0);
Set
을 이용할 수 있습니다.
const names = ['Lee', 'Kim', 'Park', 'Lee', 'Kim'];
const uniqueNamesWithArrayFrom = Array.from(new Set(names));
const uniqueNamesWithSpread = [...new Set(names)];
두 객체를 별도 변수에 합쳐줄 수 있습니다.
const person = {
name: 'Han Sung Uk',
familyName: 'Han',
givenName: 'Sung Uk'
};
const company = {
name: 'Front. Inc.',
address: 'Suwon'
}
const HanSungUk = {...person, ...company};
console.log(HanSungUk);
/*{
address: "Suwon"
familyName: "Han"
giveName: "Sung Uk"
name: "Front. Inc."
}*/
// ||
// 기본값을 넣어주고 싶을 때 사용할 수 있습니다.
// participantName이 0, undefined, 빈 문자열, null일 경우 `Guest`로 할당됩니다.
const name = participantName || 'Guest';
// &&
// flag가 true일 경우에만 실행됩니다.
flag && func();
// 객체 병합에도 이용할 수 있습니다.
const makeCompany = (showAddress) => {
return {
name: 'Front. Inc.',
...showAddress && {address: 'Seoul'}
}
};
console.log(makeCompany(false));
// {name: 'Front. Inc.'}
console.log(makeCompany(true));
// {name: 'Front. Inc.', address: 'Seoul'}
const person = {
name: 'Han Sung Uk',
familyName: 'Han',
givenName: 'Sung Uk',
company: 'Front. Inc.',
address: 'Suwon'
}
const {familyName, givenName} = person;
객체를 생성할 때 프로퍼티 키를 변수 이름으로 생략할 수 있습니다.
const name = 'Han Sung Uk';
const company = 'Front';
const person = {
name,
company
}
console.log(person);
/*{name: 'Han Sung Uk', company: 'Front'}*/
함수에 객체를 넘길 경우 필요한 것만 꺼내 쓸 수 있습니다.
const makeCompany = ({name, address, serviceName}) =>{
return {
name,
address,
serviceName
}
};
const front = makeCompany({name: 'Front. Inc.', address: 'Suwon', serviceName: 'Present'});
ES6애 추가된 기능으로 객체의 키를 동적으로 생성할 수 있습니다.
const nameKey = 'name';
const emailKey = 'email';
const person = {
[nameKey]: 'Han Sung Uk',
[emailKey]: 'hansunguk6178@gmail.com'
};
console.log(person);
// {name: 'Han Sung Uk', email: 'hansunguk6178@gmail.com'}
!! 연산자를 이용하여 0, null, 빈 문자열, undefined, NaN
을 false
로 그 외에는 true
로 변경할 수 있습니다.
function check(variable){
if(!!variable){
console.log(variable);
} else{
console.log('잘못된 값');
}
}
check(null); // 잘못된 값
check(3.14); // 3.14
check(undefined); // 잘못된 값
check(0); // 잘못된 값
check('Good'); // Good
check(''); // 잘못된 값
check(NaN); // 잘못된 값
check(5); // 5