본문 바로가기
Javascript

ES12(ES2021)의 최고의 3가지 기능

by F.E.D 2022. 10. 10.

ECMASCRIPT 2022가 나와있고, ES13에 대해서도 다루겠지만, 오늘은 ES12에서 잘 정착되어, 가장 유용하게 사용하고 있는 3가지 기능에 대해서 소개해보려고 합니다.

1. Logical Assignment Operator(논리 할당 연산자)

논리할당연산자는 논리 연산을 결합할 수 있습니다.

// 컨벤션을 고수하는 방식
if (!a) {
  a = b;
}

// 또는 간략하게
a = a || b;
a = a && b;
a = a ?? b;

// 새로운 방식
a ||= b;
a &&= b;
a ??= b;

a &&=b 는 a가 참이면 b가 할당되고, a가 거짓이면 a가 할당됩니다.

a ??= b 는 a가 null이거나 undefined 이면, b가 할당되고, 아니라면 a가 할당됩니다.

처음에는 이해하기 까다로울 수 있지만, 팀에 널리 이해시키고 사용할 수 있습니다.

2. Promise.any

Promise.all과 반대로 생각하면 될 것 같네요.

Promise.all이 모든 Promise를 수행해야 then으로 넘어갈 수 있지만, Promise.any는 하나라도 수행되면 then으로 넘어갈 수 있습니다.

동시에 세 가지 요청을 합니다.

Promise.any([
    fetch('https://google.com/').then(() => 'google'),
    fetch('https://naver.com/').then(() => 'naver'),
    fetch('https://apple.com/').then(() => 'apple')
]).then((any) => {
    // 어떤 fetch가 성공해도 이리로 넘어오게 됩니다.
    console.log(any);
    // 'google'
}).catch((error) => {
    // 모든 Promise가 실패했을 시에만 넘어오게 됩니다.
    console.log(error);
});

에러도 여러개의 AggregateError에서 단일 error별로 나타날 수 있습니다.

Promise.any([
  Promise.reject(new Error("error 1")),
  ...
]).then((any) => {
  console.log(any);
}).catch((error) => {
    console.log(error.message); // "All Promises rejected";
    console.log(error.name);    // "AggregateError";
    console.log(error.errors);  // [ Error: "error 1", Error: "error 2", ...]
});

 

3. Numeric Seperaor(숫자 구분 기호)

확실히 읽기가 편해집니다.

// 이전 방식
const count  = 1000000;
const count2 = 838383838;

// 새로운 방식
const count  = 1_000_000;
const count2 = 838_383_838;

 

 

출처 : https://betterprogramming.pub/the-top-3-new-javascript-es-2021-es-12-features-im-excited-about-a3ac129efbb2

 

댓글