모든 자바스크립트 개발자가 사용할 수 있는 10가지 트릭

2021. 6. 29. 13:51스크랩

원문

 

10 Modern JavaScript Tricks Every Developer Should Use

Tips for writing short, concise, and clean JavaScript code

betterprogramming.pub

1. 조건부 객체 프로퍼티 추가

const condition = true;

const person = {
  id:1.
  name: 'seo',
  ...(condition && {age:16}),
}

2. 객체 내 프로퍼티 존재여부 확인

const person = {name:'seo', salary: 1000};

console.log('salary' in person); // true

3. 객체 내 동적 프로퍼티 네임 할당

const dynamic = 'locale'

let person = {
  name: 'seo',
  [dynamic] : 'ko-KR'
}

// {name:'seo' , locale:'ko-KR'}

4. 동적 객체 분해 할당

const dynamic = 'name';
const person = {name:'seo', salary: 1000};

const {name:lastName} = person;
const {[dynamic]:lastName2} = person

console.log(lastName, lastName2); // 'seo', 'seo'

5. Nullish 집약(Coalescing)

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

const cannotBeZero = 0 || 5;
console.log(cannotBeZero); // returns 5const canBeZero = 0 ?? 5;
console.log(canBeZero); // returns 0

6. 옵셔널 체이닝

const book = { id:1, title: 'Title', author: null };// normally, you would do this
console.log(book.author.age) // throws error
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

7. !!를 활용한 불린 전환

const greeting = 'Hello there!';
console.log(!!greeting) // returns trueconst noGreeting = '';
console.log(!!noGreeting); // returns false

8. 빠른 String과 Integer 전환

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'

9. 배열 안에 Falsy value 확인하기

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

10. Flat을 활용한 배열 평탄화

const arr = [0, 1, 2, [[[3, 4]]]];console.log(arr.flat(2)); // returns [0, 1, 2, [3,4]]