본문 바로가기

Language/JavaScript

<ES2020> ES2020 Features

 

1. 소개

 - ES2020 에서는 드디어 BigInt와 matchAll이 추가되었다. 그 외에도 globalThis와 옵셔널체이닝, 널병합연산자 등 편의를 위해 자주 쓰이는 기능들이 추가되었다.

 

2. 기능

* BigInt

 - 자바스크립트의 숫자 최댓값은 2^53 - 1로 제한되어있다. 더 큰 정수를 저장할 수 없는 것은 아니지만 처리할때 문제가 발생하곤 한다.

 

let limit = Number.MAX_SAFE_INTEGER;
console.log(limit); // 9007199254740991
limit++;
console.log(limit); // 9007199254740992
limit++;
console.log(limit); // 9007199254740992
limit++;
console.log(limit); // 9007199254740992
console.log(typeof limit); // number

 

 - ES2020에서는 BigInt 라는 객체가 도입되었다.

 

let bigNum = BigInt(9007199254740991);
console.log(bigNum); // 9007199254740991n
bigNum++;
console.log(bigNum); // 9007199254740992n
bigNum++;
console.log(bigNum); // 9007199254740993n
bigNum++;
console.log(bigNum); // 9007199254740994n
console.log(typeof bigNum); // bigint

 

 - bigint를 통해 더 큰 숫자를 처리할 수 있게 되었다. 그러나 이는 BigInt끼리만 계산되며, 소수점은 표현할 수 없다.

 

 - 그러나 일반 숫자와 크기비교 및 정렬은 가능하다. 게다가 0n은 0과 같으므로 falsy값 이다.

 

* MatchAll

 

const reg = /\w+/g;
const str = 'Hello Harry and IU';
const regs = str.matchAll(reg); // Object [RegExp String Iterator] {}
console.log(Array.from(regs));
/*
[
  [ 'Hello', index: 0, input: 'Hello Harry and IU', groups: undefined ],
  [ 'Harry', index: 6, input: 'Hello Harry and IU', groups: undefined ],
  [ 'and', index: 12, input: 'Hello Harry and IU', groups: undefined ],
  [ 'IU', index: 16, input: 'Hello Harry and IU', groups: undefined ]
]
*/

 

 - matchAll 메서드는 문자열에서 일치하는 결과들을 모두 담아 이터레이터 형식으로 반환한다. 

 

 

* Global This

 - ES2020 이전에는 브라우저 전역객체외 Node JS의 전역객체가 달랐다. 브라우저는 window 라는 전역객체를 사용하며, Node JS는 global을 사용한다.

 

 - ES2020부터는 globalThis라는 키워드로 통일되었다. 기존에 사용한 전역객체도 사용가능하며 비교연산자를 통해 비교하면 같음을 알 수 있다.

 

* Optional Chaining

const person1 = {
  name: 'harry',
  age: 20,
};

const person2 = {
  name: 'IU',
  age: 29,
  job: {
    name: 'singer',
    location: 'Seoul',
  },
};

 

 - 위와 같이 사람을 나타내는 객체가 있다고 가정하자. 이 때, 각 사람들의 직업명을 알고 싶다면 아래와 같이 접근할 것이다.

 

console.log(person1.job.name); 
// Cannot read property 'name' of undefined

 

 - 없는 프로퍼티에 접근했기 때문에 위와 같은 에러를 보여주고 중지된다. 따라서 job이라는 프로퍼티를 갖고있는지 먼저 체크해야한다. 이를 줄여서 표현하면 아래와 같이 작성할 수 있다.

 

console.log(person1.job && person1.job.name); // undefined
console.log(person2.job && person2.job.name); // singer

 

 - 위는 그나마 단순한 객체이기 때문에 덜 복잡하다. 그러나 깊이가 깊은 객체의 경우에는 코드가 많이 복잡해질 수 있다. 이를 ES2020에서는 옵셔널 체이닝 연산자 ?. 로 해결하였다.

 

console.log(person1.job?.name); // undefined
console.log(person2.job?.name); // singer

 

 - 옵셔널 체이닝 연산자로 job이 있는지 확인을 하는 것이 명확하게 읽히며, 코드의 길이도 훨씬 짧아졌음을 알 수 있다.

 

* Nullish Coalescing

const x = 20;
console.log(x || '값 없음');
// 20

 

 - 위와 같은 코드를 자주 썼을 것이다. x에 값이 있는지를 체크하여 없으면 뒤의 값을 표시하게 하는 코드이다. 이는 값이 falsy한지를 체크하고, falsy하지 않은 값을 찾는다. 비슷하게 &&를 사용하여 falsy를 찾기도한다.

 

 - 위의 코드에서 0을 할당한다면 어떻게 될까. 분명 값은 할당되었는데 0이 falsy하므로 '값 없음'이 출력될 것이다.

 

 - 이런 문제를 해결한 것이 널 병합 기능이다. nullish한 값(null과 undefined) 를 구분한다.

 

const x = 0;
console.log(x ?? '값 없음');
// 0

 

* Promise allSettled

 - 기존에 모든 프로미스를 실행시키는 Promise.all 메서드를 알고 있을 것이다. 이는 프로미스들 중 하나만 실패해도 catch로 이동한다는 문제가 있었다. 

 

 - allSetteld 메서드는 실패와 상관없이 모든 프라미스를 실행하여 개별적으로 성공과 실패 여부를 알려준다.

 

const promises = [
  new Promise((res) => setTimeout(res, 1000)),
  new Promise((res) => setTimeout(res, x)),
  new Promise((res) => setTimeout(res, 1000)),
];
Promise.allSettled(promises).then((data) => console.log(data));

/*
[
  { status: 'fulfilled', value: undefined },
  { status: 'rejected', reson: ReferenceError: x is not defined ... },
  { status: 'fulfilled', value: undefined }
]
*/

 

* Dynamic import

 - ES2020에서 동적 import가 추가 되었다. 

 

if (condition) {
  const module = await import("./hello.js");
  module.func("hi")
}

 

 - 말 그대로 필요한 경우에 해당 모듈을 가져오는 것이다.

 

* Modul Namespace Exports

 - ES2020 이전에도 import에서는 다음의 문법을 사용할 수 있었다.

 

import * as utils from './utils.js'

 

 - ES2020 부터는 export에서도 동일한 문법을 사용할 수 있다.

 

export * as utils from './utils.js'

 

 - 이는 아래의 코드와 동일한 역할을 한다.

 

import * as utils from './utils.js'
export { utils }

 

 - 기존에는 export * from "..." 를 한곳에서 여러번 사용할 경우 이름이 충돌했으나, 이제는 네임스페이스를 통해 이름 충돌을 방지할 수 있다.

 

// moduleA.js
export const x = 1;
export const y = 2;

// moduleB.js
export const y = "1";
export const z = "2";

//
// modules.js
export * from "./moduleA";
export * from "./moduleB"; // error

 

* Import Meta

 

<script type="module" src="hello.js"></script>
console.log(import.meta); // {url: "file://home/user/hello.js"}

 

 - import.meta 객체를 통해 모듈에 대한 정보를 확인할 수 있다.

 

 


참고

 

 

 

 

10 New JavaScript Features in ES2020 That You Should Know

Good news – the new ES2020 features are now finalised! This means we now have a complete idea of the changes happening in ES2020, the new and improved specification of JavaScript. So let's see what those changes are. #1: BigIntBigInt, one of the most ant

www.freecodecamp.org

 

 

(ECMAScript) ES2020의 변화

2020년, ES2020이 나왔습니다. 이제는 더 이상 ES11같은 숫자와 병용하지 않아도 될 것 같네요. 그냥 ES2020으로 부르겠습니다. 큰 기능보다는 편의기능이 계속 추가되고 있습니다. matchAll 문자열에서

www.zerocho.com

 

ES2020, ES2021에 추가된 기능

ES2020, ES2021에 추가된 기능을 정리해 보았다.

velog.io

 

 

'Language > JavaScript' 카테고리의 다른 글

<JS> 특수 값과 레퍼런스  (0) 2021.12.23
<ES2021> ES2021 Features  (0) 2021.10.25
<JS> 제너레이터  (0) 2021.10.17
<ES10> ES2019 Features  (0) 2021.10.11
<ES9> ES2018 Features  (0) 2021.10.10