원문 : https://betterprogramming.pub/10-modern-javascript-tricks-every-developer-should-use-377857311d79
10 Modern JavaScript Tricks Every Developer Should Use
Tips for writing short, concise, and clean JavaScript code
betterprogramming.pub
원문 작성자 : https://haseebanwar.net
Haseeb Anwar - Full-Stack Developer
A full-stack software engineer who reads, writes, helps, and makes beautiful applications with React and Node. Other hobbies include eating and sleeping.
haseebanwar.net
우리나라에서는 ‘한심좌’로 알려진 유명한 틱톡커가 있습니다.
한심좌는 틱톡에서 이전 영상에서 보이는 모든 일들을 간단하게 단순화합니다.(이전 영상의 내용 자체가 단순하진 않지만요😂).
오늘은 자바스크립트 코드를 좀 더 짧고, 간결하고, 클린하게 만드는 10가지 팁들을 소개해보려고 합니다.
1. 조건부로 개체에 속성 추가하기
spread연산자
(…)를 사용해 조건부로 객체에 속성을 추가할 수 있습니다.
const condition = true;
Const person = {
id : 1, name : ‘Sally’, …(condition &&{age :23}),
};
&&연산자
는 condition
값이 참일 때 뒤의 값을 반환합니다.condition
의 값은 true이므로 개체 {age : 16}이 반환되고, person
객체의 일부로 spread 됩니다.
condition이 false라면 어떻게 될까요?
const condition = true;
const person = {
id : 1, name : ‘Sally’, …(false)}
console.log(person); // {id : 1, name : ‘sally’}
spread + false는 person
객체에 영향을 미치지 않습니다.
2. 개체에 속성이 있는지 확인하기
in
키워드를 사용해 javascript 객체에 속성이 있는지의 여부를 확인할 수 있다는 사실을 알고 계셨나요?
const duck = {
name: "Sally",
age: 10,
};
console.log("name" in duck); // returns true
console.log("hobby" in duck); // returns false
3. 객체의 동적 속성 이름
동적 키(dynamic key)로 객체의 속성을 간단하게 설정할 수 있습니다.
그냥 ['key_name']
표기법을 사용하기만 하면 됩니다.
const dynamic = "flavor";
let item = {
name: "Biscuit",
[dynamic]: "Chocolate",
};
console.log(item); // { name: 'Biscuit', flavor: 'Chocolate' }
객체의 속성을 참조하고 싶을 때도, 동적 키(dynamic key)를 사용할 수 있습니다.
const keyName = "name";
console.log(item[keyName]); //returns 'Biscuit'
(+ 타입스크립트에서는 인덱스 시그니처(index signature)를 통해 동적 키(dynamic key)와 value의 타입을 명시해 줄 수 있습니다.)
interface itemType {
[key: string]: string;
}
const dynamic = "flavor";
let item: itemType = {
[dynamic]: "Chocolate",
};
console.log(item); // {"flavor": "Chocolate"}
4. 동적 키를 사용한 객체 구조 분해
이제 우리는 변수를 구조화하고 표기법을 사용해 바로 이름을 바꿀 수 있다는 것을 알게 되었습니다.
그런데, 키 이름을 모르거나 키 이름이 동적일 때도 객체의 속성을 구조화할 수도 있다는 것을 알고 계셨나요?
먼저 구조화(별칭으로 구조화)하는 동안 변수 이름을 바꾸는 방법을 살펴보겠습니다.
const duck = { id: 1, name: "sally" };
const { name: duckName } = duck;
console.log(duckName); // returns 'sally'
이제, 동적 키로 속성을 구조화해 보겠습니다.
const templates = {
hello: "Hello there",
bye: "Good bye",
};
const templateName = "bye";
const { [templateName]: template } = templates;
console.log(template); // returns 'Good bye'
5. 병합 무효화, ??연산자
??연산자
는 변수가 null
인지 undefined
인지 확인하고 싶을 때 유용하게 사용될 수 있습니다.
왼쪽 피연산자가 null
이거나 undefined
일 경우 오른쪽 피연산자를 반환하고, 그렇지 않으면 왼쪽 피연산자를 반환합니다.
const foo = null ?? "Hello";
console.log(foo); // returns 'Hello'
const bar = "Not null" ?? "Hello";
console.log(bar); // returns `Not null`
const baz = 0 ?? "Hello";
console.log(baz); // returns 0
세번째 예시에서는 0이 반환됩니다.
자바스크립트에서 0은 Falsy한 값으로 간주하지만,null
이나 undefined
가 아니기 때문입니다.||(or)연산자
를 사용할 수 있겠다고 생각할 수 있지만, 이 두 연산자는 차이점이 있습니다.
const cannotBeZero = 0 || 5; // false || true
console.log(cannotBeZero); // returns 5
const canBeZero = 0 ?? 5;
console.log(canBeZero); // returns 0
6. 옵셔널 체이닝(?.)
TypeError: Cannot read property ‘foo’ of nulls
혹시 여러분도 위와 같은 에러를 싫어하시나요?
이 에러는 모든 자바스크립트 개발자들에게 골칫거리입니다.
옵셔널 체이닝(optional Chaining)은 이 에러를 해결하기 위해 도입되었습니다.
함께 살펴봅시다.
const book = { id: 1, title: "Title", author: null };
//console.log(book.author.age) // 위 콘솔은 에러를 발생시킵니다.
console.log(book.author && book.author.age); // returns null(no error)
// with optional chaining
console.log(book.author?.age); // returns undefined
// or deep optional chaining
console.log(book.author?.address?.city); // returns undefined
아래와 같이 함수와 함께 옵셔널 체이닝을 사용할 수도 있습니다.
const duck = {
name: "Sally",
age: 10,
printDuckInfo: function () {
return `${this.name}, ${this.age}`;
},
};
console.log(duck.printDuckInfo()); // returns 'Sally, 10'
console.log(duck.doesNotExist?.()); // returns undefined
7.!!연산자
를 사용한 Boolean 변환
!!연산자
를 사용하여 식의 결과를 true 또는 false로 빠르게 변환할 수 있습니다.
const greeting = "Hello there!";
console.log(!!greeting); // returns true
const noGreeting = "";
console.log(!!noGreeting); // returns false
8.문자열과 정수 변환
+연산자
를 사용해 다음과 같이 문자열을 숫자로 빠르게 변환시킬 수 있습니다.
const stringNumer = "123";
console.log(+stringNumer); // returns integer 123
console.log(typeof +stringNumer); // returns 'number'
숫자를 문자열로 빠르게 변환하기 위해, +연산자
뒤에 빈 문자열 ""을 입력할 수도 있습니다.
const myString = 25 + "";
console.log(myString); // returns '25'
console.log(typeof myString); // returns 'string'
이러한 유형 변환은 매우 편리하지만, 명확성과 코드 가독성이 떨어집니다.
따라서 현업 코드에 적용하고자 할 때는 생각을 많이 해봐야 합니다.
하지만, 코드 골프에서는 사용하는 것을 주저하지 마세요.
(code golf : 레크리에이션 컴퓨터 프로그래밍 대회의 일종으로, 참여자들은 특정한 알고리즘을 구현하는 가장 짧은 잠재적 소스 코드를 달성하기 위해 고군분투함)
9. 배열의 잘못된 값 확인
여러분은 filter
, some
, every
와 같은 배열 메서드에 익숙해야 합니다.
하지만, Boolean
메서드를 사용하여 참값을 테스트할 수도 있다는 것 또한 알고 있어야 합니다.
const myArray = [null, false, "Hello", undefined, 0];
// filter falsy values
const filtered = myArray.filter(Boolean);
console.log(filtered); // returns ['Hello']
// check if at least one value is truthy
const anyTruthy = myArray.some(Boolean);
console.log(anyTruthy); // returns true
// check if all values are truthy
const allTruthy = myArray.every(Boolean);
console.log(allTruthy); // returns false
위와 같은 배열 메서드는 콜백 함수를 사용하므로 콜백 함수로 Boolean을 전달합니다.
Boolean 자체는 인수를 사용하고 인수의 진실성(truthiness)에 따라 true 또는 false를 반환합니다.
따라서 아래와 같이 정의할 수 있습니다.
myArray.filter((val) => Boolean(val));
이렇게도 가능합니다.
myArray.filter(Boolean);
10. 배열의 배열 병합하기
prototype Array에는 배열에서 단일 배열을 만들 수 있는 메서드flat
이 있습니다.
const myArray = [{ id: 1 }, [{ id: 2 }], [{ id: 3 }]];
const flattedArray = myArray.flat();
// returns [ { id: 1 }, { id: 2 }, { id: 3 } ]
중첩된 배열 구조가 얼마나 깊이 평면화되어야 하는지를 지정하는 깊이 수준을 정의할 수도 있습니다.
const arr = [0, 1, 2, [[[3, 4]]]];
console.log(arr.flat(2)); // returns [0, 1, 2, [3,4]]
끝까지 읽어주셔서 감사합니다.
부디 이 기사가 여러분에게 유용하게 쓰이길 바랍니다.