프로그래머스 데브코스
[JavaScript] JavaScript의 10가지 코드 트릭
hellosonic
2023. 10. 3. 14:34
✅ 01. 구조 분해 할당을 이용한 변수 swap
let a = 5, b = 10;
[a, b] = [b, a]
console.log(a,b); // 10 5
배열 구조 분해 할당
ES6에서 배열의 각 요소를 추출하여 변수 리스트에 할당한다.
const arr = [1,2,3];
const [one, two, three] = arr;
console.log(one, two, three); // 1, 2, 3
객체 구조 분해 할당
객체의 각 프로퍼티를 추출하여 변수 리스트(객체 형태)에 할당한다. 할당 기준은 키 이다.
const obj = { firstName : "Minho", lastName : "Hwang" };
const { lastName, firstName } = obj;
console.log(firstName, lastName);
✅ 02. 배열 생성으로 루프 제거하기
5에서 9까지의 합을 구하는데에 루프 대신 배열을 사용
const arr = Array.from({length:5}, (element, idx) => idx+5);
const sum = arr.reduce((currValue, s) => { return currValue + s }, 0);
console.log(sum); // 35
✅ 03. 배열 내 같은 요소 제거하기
중복 제거는 Set으로 한다.
const name = ["Lee", "Kim", "Park", "Lee", "Kim"];
console.log(Array.from(new Set(name)));
console.log([...new Set(name)]); // 스프레드 문법 이용
✅ 04. Spread 연산자를 이용한 객체 병합
두 객체를 합칠 수 있다.
const person = {
name : 'Hwang Minho',
familyName : 'Hwang',
givenName : 'Minho',
};
const hobby = {
name : 'Watching-Soccer',
address : 'Seoul',
};
const newObj = { ...person, ...hobby };
console.log(newObj);
// {
// name: 'Watching-Soccer', // -> 같은 키는 우선순위에 따라 결정됨
// familyName: 'Hwang',
// givenName: 'Minho',
// address: 'Seoul'
// }
✅ 05. &&와 || 활용
// participanName이 0, undefined, 빈 문자열, null일 경우 'Guest'로 할당
const name = participantName || 'Guest';
// flag 가 true일 때만 실행
flag && func();
const makePerson = (showAddress) => {
return {
name : 'Hwang',
...showAddress && { address :'Seoul' } // sowAddress가 true면 병합
}
}
console.log(makePerson(false));
console.log(makePerson(true));
✅ 06. 구조 분해 할당 사용
객체에서 필요한 것만 꺼내쓰기
const person = {
name: 'Lee Sun-Hyoup',
familyName: 'Lee',
givenName: 'Sun-Hyoup',
company: 'Cobalt. Inc.',
address: 'Seoul',
}
const { familyName, givenName } = person;
console.log(familyName); // Lee
console.log(givenName); // Sun-Hyoup
✅ 07. 객체 생성시 키 생략하기
객체 생성 시 프로퍼티 키를 변수 이름으로 할 수 있습니다.
const name = "Hwang Minho";
const address = "Seoul";
const person = {
name,
address,
}
console.log(person);
// { name: 'Hwang Minho', address: 'Seoul' }
✅ 08. 비구조화 할당 사용하기
const makePerson = ( { name, address, hobby } ) => {
return {
name,
address,
hobby,
}
};
const me = makePerson( { name: 'Hwang', address: 'Seoul', hobby: 'soccer'});
console.log(me); // { name: 'Hwang', address: 'Seoul', hobby: 'soccer' }
✅ 09. 동적 속성 이름
ES6에 추가된 기능. 객체의 키를 동적으로 생성
const nameKey = 'name 키 동적생성';
const emailKey = 'email';
const person = {
[nameKey]: 'Hwang',
[emailKey] : '1234@naver.com',
}
console.log(person); // { 'name 키 동적생성': 'Hwang', email: '1234@naver.com' }
✅ 10. !! 연산자를 사용하여 Boolean 값으로 바꾸기
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
🙆🏻♂️ 피드백
파이썬으로 공부하다가 자바스크립트 공부하려니 헷갈리는 문법이 너무 많았는데, 이렇게 자바스크립트에서 자주 사용하는 코드 트릭을 배울 수 있는 기회가 주어져서 좋았다. 앞으로 자바스크립트로 코딩하는데에 더 낫겠지..