ECMAScript 2020이 밝았다
Object.fromEntries
Object.entries를 통해 object의 key와 value를 지닌 배열을 가져올 수 있었다면, 이번에 나온 Object.fromEntries는 역으로 배열에서 object를 반환해준다
const entries = new Map([
['foo', 'bar'],
['baz', 42]
]);
const obj = Object.fromEntries(entries);
console.log(obj);
// expected output: Object { foo: "bar", baz: 42 }
Dynamic import
import는 프로미스를 반환하게 되고(함수를 상속한 것은 아님) 필요할 때 모듈을 사용할 수 있도록 해준다. 이를 통해 퍼포먼스 향상, 모듈 로드시에 에러 핸들링을 가능하게 해주고 각 모듈간의 레이스 컨디션을 막아줄 수 있다.
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);
})();
Promise.allSettled
promise의 결과가 이행되든 거절되든 상관 없이 그 결과를 모두 가져다 준다.
function reflect(promise) {
return promise.then(
(v) => {
return { status: 'fulfilled', value: v };
},
(error) => {
return { status: 'rejected', reason: error };
}
);
}
const promises = [ fetch('index.html'), fetch('https://does-not-exist/') ];
const results = await Promise.all(promises.map(reflect));
const successfulPromises = results.filter(p => p.status === 'fulfilled');
//--------------------------------------------------------------
const promises = [ fetch('index.html'), fetch('https://does-not-exist/') ];
const results = await Promise.allSettled(promises);
const successfulPromises = results.filter(p => p.status === 'fulfilled');
String.prototype.matchAll
그동안 사용했던 String.prototype.match는 정확히 일치하는 것만 반환했지만 String.prototype.matchAll은 Regex pattern capture groups에 접근 가능한 이터레이터를 반환한다.
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' }
// ]
// ]
Optional Chaining
오브젝트에 접근할 때 레퍼런스에러 핸들링하기 불편했는데, 이번에 나온 키워드로 좀 편해질듯! 코드 참고!
// before
const title = data && data.article && data.article.title
// after
const title = data?.article?.title
GlobalThis
그동안 global this는 환경에 따라 window, self, global… keyword가 다양했는데 globalThis로 통일!
Nullish Coalescing Operator
truthy, falsy한 값들은 디폴트 값 주기 힘들었는데 편해질듯!
"" || "default value"
// default value
"" ?? "default value"
// ""
import.meta
현재 실행 중인 모듈에 호스트 관련 메타데이터를 추가!
console.log(import.meta.url)
// file:///Users/pawelgrzybek/main.js
Resource
https://pawelgrzybek.com/whats-new-in-ecmascript-2020/ https://dev.to/shadid12/new-javascript-features-coming-in-2020-that-will-surely-rock-your-world-54b