What's new in ECMAScript 2020

栏目: IT技术 · 发布时间: 5年前

内容简介:The list of new ECMAScript 2020 features is set in stone. Similarly, how I did it in2016,TheIn contrast to static modules introduced in ECMAScript 2015,

The list of new ECMAScript 2020 features is set in stone. Similarly, how I did it in2016, 2017 ,2018 and2019, let's have a look at what's coming this year and a few practical examples.

  • String.prototype.matchAll by Jordan Harband
  • import() by Domenic Denicola
  • BigInt – arbitrary precision integers by Daniel Ehrenberg
  • Promise.allSettled by Jason Williams, Robert Pamely and Mathias Bynens
  • globalThis by Jordan Harband
  • for-in mechanics by Kevin Gibbons
  • Optional chaining by Gabriel Isenberg, Claude Pache, Dustin Savery
  • Nullish coalescing Operator by Gabriel Isenberg
  • import.meta by Domenic Denicola
  • export * as ns from “mod”

String.prototype.matchAll by Jordan Harband

The match() method from String.prototype returns only complete matches, but doesn't return any information about particular Regex groups. Thanks to Jordan Harband for the String.prototype.matchAll proposal that returns a lot more info than match() . The returned iterator apart from exact matches give us an access to all Regex pattern capture groups. Do you remember named capture groups by Gorkem Yakin and Daniel Ehrenberg added to ECMAScript 2018? The matchAll() method works really well with it. The example will clarify it.

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' }
//   ]
// ]

import() by Domenic Denicola

In contrast to static modules introduced in ECMAScript 2015, dynamic imports proposed by Domenic Denicola can be fetched on-demand. This function-like format (it doesn't inherit from Function.prototype ) returns a promise and it is very powerful. Things like: on-demand import, computed module name and execution inside of a script became possible.

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);
})();

BigInt – arbitrary precision integers by Daniel Ehrenberg

Thanks to Daniel Ehrenberg Number.MAX_SAFE_INTEGER is no longer a restriction in JavaScript land. BigInt is a new primitive that can represent integers with arbitrary precision. You can convert a number to new bigint type using BigInt function or by appending n suffix to a numeric value.

Number.MAX_SAFE_INTEGER
// 9007199254740991

Number.MAX_SAFE_INTEGER + 10 -10
// 9007199254740990 :-1:

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

Promise.allSettled by Jason Williams, Robert Pamely and Mathias Bynens

Since the ECMAScript ES2015 JavaScript has supported only two promise combinators: Promise.all() and Promise.race() . Thanks to Jason Williams, Robert Pamely and Mathias Bynens we now have access to Promise.allSettled() . Use it to handle when all promises are settled regardless of the result (fulfilled or rejected). Look ma, no 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`));

There is a Promise.any() potentially joining ECMAScript language soon. I described them all in “Promise combinators explained” some time ago.

globalThis by Jordan Harband

So what is a global this in JavaScript? It is a window in the browser, self in a worker, global in Node.js and what else… This mess is over! Thanks to Jordan Harband we now have access to globalThis keyword .

for-in mechanics by Kevin Gibbons

ECMAScript left behind a detailed description of for-in loop order. Thanks to Kevin Gibbons who finally put some TLC and defined a set in stone set of rules for for-in mechanics .

Optional chaining by Gabriel Isenberg, Claude Pache, Dustin Savery

Long chains of object property accesses can be error-prone and unconformable to read. Thanks to Gabriel Isenberg , Claude Pache and Dustin Savery this thing cannot be simpler now. If you are a TypeScript user you won't find anything new here because this feature has been implemented in version 3.7 . Love it!

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

// after
const title = data?.article?.title

Nullish coalescing Operator by Gabriel Isenberg

The nullish coalescing proposal adds a new short-circuiting operator to handle default values. Gabriel Isenberg did fantastic work. This feature goes hand in hand with optional chaining. In contrast to || operator, nullish coalescing operator ?? evaluating only when left-hand side value is strictly null or undefined .

"" || "default value"
// default value

"" ?? "default value"
// ""
const title = data?.article?.title ?? "What's new in ECMAScript 2020"

import.meta by Domenic Denicola

The import.meta proposal by Domenic Denicola adds a host-specific metadata object to the currently running module.

console.log(import.meta.url)
// file:///Users/pawelgrzybek/main.js

export * as ns from “mod”

This is a useful addition to the specification that allows developers to export another module's namespace exotic object under the new name.

export * as ns from "mod"

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Google總部大揭密

Google總部大揭密

史蒂芬.李維 / 陳重亨 / 財信 / 2011-11

∣如果有一天,Google的搜尋引擎突然故障 ∣GMAIL信件全數消失 ∣Google Maps、Google Docs、Google行事曆等所有雲端服務全面停擺 ∣我們該怎麼辦?! 歷史上像Google如此成功,且廣受推崇的企業可沒幾家。它改變了網路的使用方式,也成了我們生活不可或缺的一部分。這到底是怎麼辦到的? 《連線》雜誌資深主筆史蒂芬.李維史無前例同時取得LS......一起来看看 《Google總部大揭密》 这本书的介绍吧!

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具