개발공부/JavaScript

자바스크립트에서 유용하게 사용할 수 있는 팁

개발자 찐빵이 2022. 2. 25. 08:42
728x90
반응형

1. Nullish Coalescing​

function print(something){
    const message = something ?? 'there is no message';
    console.log(message);
}

something이 null/undefined 인 경우 "there is no message"가 message에 들어간다.

default parameter를 사용하면
undefined 인 경우에만 적용되고,
null인 경우에는 적용되지 않는다.

2. Object Destructuring

function printStudent(student){
    const { name, age } = student;
    console.log(name);
    console.log(age);
}

객체의 반복을 줄이기 위해서 사용한다.
student.name, student.age로 반복해서 객체를 부르지 않아도 된다.

3. Spread Syntax

//object 합치기
const item = { type: 'phone', name: 'iphone pro' };
const detail = { price: 50, made: 'China' };

const iphone = { ...item, ...detail };

// 값을 덮어 씌우거나 추가할 수 있다.
iphone = { ...item, ...detail, made: 'Korea', size: 20 };

//array 합치기
let fruits = ['apple', 'banana', 'orange'];
let vegetables = ['carrot', 'onion', ''cucumber'];

let vegetarianFood = [...fruits, ...vegetables];

// 원하는 위치에 값을 추가할 수 있다.
vegetarianFood = [...fruits, 'strawberry', ...vegetables];

객체나 배열을 합치고 싶을 때 사용한다.

4. Optional Chaining

if(iphone?.price == 50{
    ...
}

?를 사용해서 있는 경우에 안에 있는 값을 확인하도록 할 수 있다.

5. Array 내장 함수

  1. filter
    원하는 조건의 아이템만 가져올 때 사용된다.
    const odd = items.filter(num => num % 2 == 1);
  2. map
    배열 내 모든 아이템의 값을 변경하고 싶을 때 사용된다.
    const double = items.map(num => num * 2);
  3. reduce
    배열 내 모든 값을 더하고 싶을 때 사용된다.
    const sum = items.reduce((a, b) => a + b, 0);

이게 연속적으로 일어난다면 chaining을 할 수 있다.

const reseult = items
    .filter(num => num % 2 == 1)
    .map(num => num * 2)
    .reduce((a, b) => a + b, 0);
반응형