swap
할 수 있음let a = 5, b = 10;
[a, b] = [b, a];
console.log(a, b); // 10 5
let sum = 0;
for (let i = 5; i < 10; i += 1) {
sum += i;
}
const sum = Array
.from(new Array(5), (_, k) => k + 5) // new Array 반환 [undefined, undefined, ..]
// Array.from() 두번째 인자는 mapFn, 그래서 _는 undefined, k는 인덱스
// [5, 6, 7, 8, 9] 반환
.reduce((acc, cur) => acc + cur, 0);
console.log(sum) // 35
// Set를 이용할 수 있음.
const names = ['Kim', 'Lee', 'Park', 'Lee', 'Kim'];
const uniqueNamesWithArrayFrom = Array.from(new Set(names)); // new Set(names)는 Set(3) {'Kim', 'Lee', 'Park'}을 반환
const uniqueNamesWithSpread = [...new Set(names)]
console.log(uniqueNamesWithArrayFrom); // [ 'Kim', 'Lee', 'Park' ]
console.log(uniqueNamesWithSpread); // [ 'Kim', 'Lee', 'Park' ]
const person = {
name: 'Kim Gun-Yeop',
familyName: 'Kim',
givenName: 'Gun-Yeop'
};
const company = {
name: 'Not Yet',
address: 'Seoul'
};
const kimGunYeop = { ...person, ...company };
console.log(kimGunYeop);
// {
// address: “Seoul”
// familyName: “Kim”
// givenName: “Gun-Yeop”
// name: "Not Yet" // 같은 키는 마지막에 대입된 값으로 정해진다.
// }
/// ||
// 기본값을 넣어주고 싶을 때 사용할 수 있음.
// participantName이 0, undefined, 빈 문자열, null일 경우 'Guest'로 할당됨.
const name = participantName || 'Guest';
/// &&
// flag가 true일 경우에만 실행됨.
flag && func();
// 객체 병합에도 이용할 수 있음.
const makeCompany = (showAddress) => {
return {
name: 'Not Yet',
...showAddress && { address: 'Seoul' }
}
};
console.log(makeCompany(false));
// { name: 'Not Yet' }
console.log(makeCompany(true));
// { name: 'Not Yet', address: 'Seoul' }
const person = {
name: 'Kim Gun-Yeop',
familyName: 'Kim',
givenName: 'Gun-Yeop'
company: 'Not Yet',
address: 'Seoul',
}
const { familyName, givenName } = person;
const name = 'Kim Gun-Yeop';
const company = 'Not Yet';
const person = {
name,
company
}
console.log(person);
// {
// name: 'Kim Gun-Yeop',
// company: 'Not Yet',
// }
const makeCompany = ({ name, address, serviceName }) => {
return {
name,
address,
serviceName
}
};
const cobalt = makeCompany({ name: 'Not Yet', address: 'Seoul', serviceName: 'Present' });
const nameKey = 'name';
const emailKey = 'email';
const person = {
[nameKey]: 'yeopto',
[emailKey]: 'yeopto@zzang.com'
};
console.log(person);
// {
// name: 'yeopto',
// email: 'yeopto@zzang.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
참고 - 프로그래머스 코딩테스트 광탈 방지 A to Z : JavaScript