[INFO] ECMAScript 2020

Dev_min·2020년 4월 9일
0

새로운 점

[원문] Pawel Grzybek, https://pawelgrzybek.com/whats-new-in-ecmascript-2020/
[번역글] https://ui.toast.com/weekly-pick/ko_20200409/?fbclid=IwAR2YWdr8_lOegZflaJSdAfG9nuTApDd3wNvRLmvA-KmNXNQhoNPzDUDqByo

1. String.prototype.matchAll
:String.prototype의 match() 메서드는 정확히 일치하는 결과만을 반환하고 특정 정규 표현식 그룹에 관한 정보는 어떤 것도 제공하지 않았지만, String.prototype.matchAll을 사용하여 더 많은 정보를 반환할 수 있다.

const text = "From 2019.01.29 to 2019.01.30";
const regexp = /(?<year>\d{4}).(?<month>\d{2}).(?<day>\d{2})/gu;
const results = text.match(regexp);

console.log(results);
// [ '2019.01.29', '2019.01.30' ]
const text = "From 2019.01.29 to 2019.01.30";
const regexp = /(?<year>\d{4}).(?<month>\d{2}).(?<day>\d{2})/gu;
const results = Array.from(text.matchAll(regexp));

console.log(results);
// [
//   [
//     '2019.01.29',
//     '2019',
//     '01',
//     '29',
//     index: 5,
//     input: 'From 2019.01.29 to 2019.01.30',
//     groups: [Object: null prototype] { year: '2019', month: '01', day: '29' }
//   ],
//   [
//     '2019.01.30',
//     '2019',
//     '01',
//     '30',
//     index: 19,
//     input: 'From 2019.01.29 to 2019.01.30',
//     groups: [Object: null prototype] { year: '2019', month: '01', day: '30' }
//   ]
// ]

2. import()
: 정적 모듈과는 반대로 동적 가져오기로 필요에 따라 모듈을 가져올 수 있다. 함수형 구문인 import()는 Promise를 반환

const modulePage = 'page.js';
import(modulePage)
    .then((module) => {
      module.default();
    });
(async () => {
  const helpersModule = 'helpers.js';
  const module = await import(helpersModule)
  const total = module.sum(2, 2);
})();

3. BigInt 임의 정밀도 정수
: BigInt는 임의 정밀도로 정수를 표현하는 새로운 원시 값이다. BigInt 함수를 사용하거나 숫자 값에 n 접미사를 붙여서 숫자를 bigint 타입으로 변환할 수 있다.

Number.MAX_SAFE_INTEGER
// 9007199254740991

Number.MAX_SAFE_INTEGER + 10 -10
// 9007199254740990 👎

BigInt(Number.MAX_SAFE_INTEGER) + 10n -10n
// 9007199254740991n 👍

4. Promise.allSettled
: ECMAScript 2015부터 JS는 프로미스를 결합하는 방법으로 Promise.all()과 Promise.race() 2가지를 사용했다. Promise.allSettled()는 fulfilled되거나 rejected된 결과와 상관없이 모든 프로미스가 실행된 후에 어떤 처리를 하고 싶을때 사용한다. catch를 사용하지 않아도 된다.

Promise.allSettled([
  fetch("https://api.github.com/users/pawelgrzybek").then(data => data.json()),
  fetch("https://api.github.com/users/danjordan").then(data => data.json())
])
  .then(result => console.log(`All profile settled`));

5. globalThis
: 자바스크립트를 공부하면서 제일 이해하기 힘들었던 this의 개념이었다. 자바스크립트에서는 전역 this, 브라우저에서는 window, 워커에서는 self, Node.js에서는 global, 그리고 다른 환경에서는 또 다른 변수를 뜻한다. 이렇게 불리던 것을 globalThis를 이용하여 활용할 수 있다.

6. optional chaining
: 객체 프로퍼티에 접근하기 위해 길게 이어진 체인은 오류가 나기 쉬우며 가독성이 좋지 않다. 하지만 TypeScript 사용자라면 optional chaining이 3.7버전에서 이미 구현되었으므로 이 기능이 새롭게 느껴지지 않을 수 있다.

// before
const title = data && data.article && data.article.title

// after
const title = data?.article?.title
profile
TIL record

0개의 댓글