Introduction to the

ES6, also known as ES2015, was officially released in June 2015. Every year after that, part of the content is revised and the ES version corresponding to the year number is released in June, for example, ES2016 to ES2020. ES2020 is the 11th edition of the ECMAScript language specification, also known as ES11.

ES2020 features (Refer to the link)

Chain merge operator

Chain judgment operator

Refer to the link

If you read an attribute inside an object, you often need to check whether the object exists, such as getting the value of list.info.base.username

Const userName = list.info.base. UserName; // Const userName = list.info.base. / / correct term (the way we commonly used) const userName = (list & list. The info & list. The info. The base && list. The info. The base. The userName) | | 'userName'.Copy the code

The userName to be fetched is at the third level of the object and requires three levels of && to fetch the value. Es2020 simplifies this by introducing the chain join operator.

const userName = list? .info?.base?.userName || 'userName';Copy the code

The chain merge operator that determines whether the object on the left is null or undefined when called. If so, it does not proceed further and returns undefined. Three usages:

  • obj? .prop // Object properties
  • obj? [expr] / / same as above
  • func? . (… Args) // Call a function or object method

The sample code

// obj? .prop let list = { info: { // base: { // userName: 'eyunhua' // } } } const userName = list? .info?.base?.userName || 'userName'; / / judgment? Is the left expression null or undefined, if not, proceed to // func? . (... args) funtion register(a, b) { console.log(a, b, 'register function'); } this.register? . (1, 2); // obj? .\[expr\] let hex = "#C0FFEE".match(/#([A-Z]+)/i)? . [0]; console.log(hex);Copy the code

Babel plug-in conversion

Install plugin @babel/plugin-syntax-optional-chaining

npm install --save-dev @babel/plugin-syntax-optional-chaining
Copy the code

Add plugin to babel.cofig.js

{
 "plugins": ["@babel/plugin-syntax-optional-chaining"]
}
Copy the code

Babeljs. IO/docs/en/bab…

The Null judgment operator

Specifies the default value when the property value is null or undefined

Refer to the link

When reading object properties, you sometimes need to specify a default value for an attribute if its value is null or undefined. Common practice is to pass | | operators specify a default value.

const userName = (list && list.info && list.info.base && list.info.base.userName) || 'userName';
Copy the code

| | or operator expression is on the left side of the expression is null, undefined, “, false, 0, on the right side of the expression will take effect. But all we want is for null or undefined to work.

Es2020 introduces a new Null judgment operator?? . Its behavior similar | |, but only the operator to the left of the value is null or undefined, will return to the right of the value.

And the chain judge operator? . Use together.

const userName = list? .info?.base?.userName ?? 'userName';Copy the code

Can be used to determine the default value of function parameters

register(a, b) {
  b = b ?? 3;
}
Copy the code

And &&, | | operators are used together, need to use parentheses to indicate priority, not an error. Precedence is given to the parts enclosed in parentheses

// Error a && b?? C // Correct (a && b)?? cCopy the code

One purpose of this operator is to judge the chain operator? .Used in conjunction with, fornullorundefinedIs set to the default value.

Babel plug-in conversion

Install the plug-in @babel/plugin-proposal-nullish-coalescing-operator

npm install --save-dev @babel/plugin-proposal-nullish-coalescing-operator
Copy the code

Add plugin to babel.cofig.js

{
 "plugins": ["@babel/plugin-proposal-nullish-coalescing-operator"]
}
Copy the code

Babeljs. IO/docs/en/bab…

import()

A syntax for asynchronously importing modules using dynamic specifiers

Refer to the link

Import commands are statically parsed by the JavaScript engine before other statements in the module are executed. The engine handles import statements at compile time, not run time. That is, import and export commands can only be at the top level of a module, not in a code block.

If we want to implement importing modules by judgment, the import command is impossible to implement.

If (page === 'home') {import home from './home'; }Copy the code

The ES2020 proposal introduces the import() function to support dynamic loading of modules

Import (specifier) // Specifier indicates the loading module location or script file addressCopy the code

The import() function returns a Promise object that will be used as an object for the then callback after successfully loading the module. Therefore, you can use the syntax of object deconstruction assignment to get the output interface.

Export const export1 = '' from import('./home.js') // home.js; . . Then (({export1, export2}) = > / / load the success callback}). The catch (err = > {/ / load failed callback});Copy the code

Import () is executed at runtime, meaning that the specified module is loaded whenever this sentence is run. Also, unlike import statements, the import() function is not statically linked to the loaded module. Import () is similar to Node’s require method, except that the former is loaded asynchronously and the latter synchronously.

Applicable occasions

  1. Load on demand (e.g. load a file or module when clicked)
  2. Conditional loading (e.g., in the if judgment module)
  3. Dynamic module paths (e.g. module paths are generated in real time)

Babel plug-in conversion

Install the plugin @babel/plugin-syntax-dynamic-import

npm install --save-dev @babel/plugin-syntax-dynamic-import
Copy the code

Add plugin to babel.cofig.js

{
"plugins": ["@babel/plugin-syntax-dynamic-import"]
}
Copy the code

Babeljs. IO/docs/en/bab…

export * as ns from ‘module’

Special syntax for use within modules

Refer to the link

In a module, modules are input and then output, and import statements can be written together with export statements. Note: Writing on a line does not actually import the interface, but merely forwards it so that it cannot be used in the current module.

export { foo, bar } from 'my_module'; Import {foo, bar} from 'my_module'; export { foo, bar };Copy the code

Before ES2020, there was a compound way to write import:

import * as someIdentifier from "someModule";
Copy the code

Es2020 introduces the corresponding export notation:

export * as someIdentifier from "someModule"; Import * as ns from "mod"; export {ns};Copy the code

More on import and export

Babel plug-in conversion

Install @babel/plugin-proposal-export-namespace-from

npm install --save-dev @babel/plugin-proposal-export-namespace-from
Copy the code

Add plugin to babel.cofig.js

{
  "plugins": ["@babel/plugin-proposal-export-namespace-from"]
}
Copy the code

Reference links:

  1. Github.com/tc39/propos…
  2. Babeljs. IO/docs/en/bab…

BigInt

A new numeric primitive for handling arbitrary precision integers

Refer to the link

JavaScript saves all numbers as 64-bit floating-point numbers, which imposes two major limitations on the representation of values.

  1. Numeric accuracy: Up to 53 binary bits (equivalent to 16 decimal bits), integers larger than this range cannot be accurately represented by JavaScript.
  2. A value greater than or equal to 2 to the power of 1024, which JavaScript cannot represent, returns Infinity.
Math.pow(2, 53) === = math.pow (2, 53) + 1 // true // For numbers greater than 2 to the power of 1024, Cannot express math.pow (2, 1024) // InfinityCopy the code

Why is the largest safe integer in JS 2 to the power of 53 minus 1?

In order to more accurately represent integers without a bit limit, ES2020 introduces the BigInt numeric type, which is different from the Number numeric type. It is only used to represent integers (large integers). There is no limit on the Number of digits, and any integer can be accurately represented. To distinguish BigInt from Number, data of type BigInt must be suffixed with n.

const a = 2172141653n; const b = 15346349309n; // BigInt can keep the precision a * b // 333344445566667777n // Common integers cannot keep the precision Number(a) * Number(b) // 33334444555566670000Copy the code

Typeof operator For BigInt data type, return BigInt

typeof 1n // bigint
Copy the code

Bigint object reference link

JavaScript natively provides BigInt objects that can be used as constructors to generate values of type BigInt. The conversion rules are basically the same as for Number(), which converts other types of values to BigInt.

BigInt(123) // 123n
BigInt('123') // 123n
BigInt(false) // 0n
BigInt(true) // 1n
Copy the code

Method of inheritance

/ / inherited from other objects BigInt. Prototype. The toString () BigInt. Prototype. The valueOf () BigInt. Prototype. ToLocaleString ()Copy the code

New method bigint.asuintn (width, BigInt) : Convert the given BigInt to a value between 0 and 2width-1. BigInt. AsIntN (width, BigInt) : The given BigInt is converted to the corresponding value between -2width-1 and 2width-1-1. Bigint.parseint (String [, radix]) : Approximate to number.parseint (), converts a string to BigInt in the specified radix.

Conversion operation reference link

Mathematical operations reference links

Other operations reference links

Used as vue props — not supported yet

Already under development, PR is in open state

Github.com/vuejs/vue/p…

Babel plug-in conversion

Install plugin @babel/plugin-syntax-bigint

npm install --save-dev @babel/plugin-syntax-bigint
Copy the code

Add plugin to babel.cofig.js

{
  "plugins": ["@babel/plugin-syntax-bigint"]
}
Copy the code

Babeljs. IO/docs/en/bab…

Promise.allSettled

The new Promise combinator does not short-circuit reference links

This method was introduced by ES2020. Take a set of Promise instances as parameters and wrap them into a new Promise instance. The packaging instance will be fulfilled only after all these parameter instances return the result, no matter fulfilled or Rejected. Once fulfilled, the state will always be fulfilled and will not become Fulfilled. After the state becomes depressing, the Promise listener receives an array of parameters, each member corresponding to an incoming promise.allSettled () Promise instance.

const resolved = Promise.resolve(42);
const rejected = Promise.reject(-1);

const allSettledPromise = Promise.allSettled([resolved, rejected]);

allSettledPromise.then(function (results) {
  console.log(results);
});
// [
//    { status: 'fulfilled', value: 42 },
//    { status: 'rejected', reason: -1 }
// ]
Copy the code

The listener receives an array, each member of which is an object corresponding to two Promise instances passed in promise.allSettled (). Each object has a status attribute, whose value can only be the string fulfilled or the string Rejected. Someday, the object has the value attribute, and the object has the reason attribute, which corresponds to the return values of the two states.

Contrast Promise. All

const p1 = new Promise((resolve, reject) => { setTimeout(() => { resolve('hello'); }, 1000); }).then(result => result) .catch(e => e); Const p2 = new Promise((resolve, reject) => {throw new Error(' Error '); }).then(result => result); .catch(e => { console.log('p2:' + e); }); // const p = Promise.allSettled([p1, p2]); const p = Promise.all([p1, p2]); p.then(function (results) { console.log(results); }).catch(err => { console.log('settled:' + err); });Copy the code

Contrast Promise. Race

Const p3 = new Promise((resolve, reject) => {// setTimeout(() => {resolve(' success ')); / /}, 2000); }); const race = Promise.race([ p3, new Promise(function (resolve, reject) { setTimeout(() => reject(new Error('request timeout')), 1000); }) ]); race.then(data => { console.log('success:', data); }).catch(error => { console.log('error:', error); });Copy the code
Similarities:

Take a set of Promise instances as parameters and wrap them into a new Promise instance

Difference:
  • state

Promise.all

  1. Both P1 and P2 instances are in statefulfilledWhen, the state of P becomesfulfilled, the return values of P1 and p2 form an array and are passed to the callback function of P
  2. As long as one of p1 and P2 isrejectedThe state of p becomesrejectedThe return value of the first reject instance is passed to p’s callback function

Promise.allSettled

This will be a big pity once it is over, and the state will not become the rejected (i.e., the catch callback will never enter P). Promise.race

One of the instances returns state, and the state of P changes and never changes again

  • The return value

Promise.all

Returns an array where each member is the result of the instance

Promise.allSettled

Each member of the array is an object. Each object has the status attribute. The value of this attribute can only be the string fulfilled or the string Rejected. Someday, the object has the value attribute, and the object has the reason attribute, which corresponds to the return values of the two states.

Promise.race

The result for each instance

  • Application scenarios

Promise.all

There are reject instances in the parameter Promise instance, and it is not possible to determine that all requests have ended

Promise.allSettled

You can be sure that all requests have ended

Promise.race

As soon as there is a return value, stop other requests immediately

String.prototype.matchAll()

Returns all matches of a regular expression in the current string

Reference links:

  1. Es6.ruanyifeng.com/#docs/regex…
  2. Developer.mozilla.org/en-US/docs/…

ES2020 before

let regex = /t(e)(st(\d?) )/g; let string = 'test1test2test3'; let matches = []; let match; while (match = regex.exec(string)) { matches.push(match); } console.log(matches); // Return the regular expression in the current string all matches (array)Copy the code

New matchAll feature in ES2020

You can fetch all matches at once, but return an Iterator instead of an array. You can loop it out with for of. The advantage of returning a traversal over an array is that the traversal is resource-efficient if the result is a large array. Iterator to array, is also more convenient, can use… The operator and array.from () will do the job.

let regex = /t(e)(st(\d?) )/g; let string = 'test1test2test3'; [...string.matchAll(regex)]; Or an Array. The from (string. MatchAll (regex));Copy the code

globalThis

A reference link for a common way to get top-level objects in different environments

Different environments have different methods for obtaining global objects

  • In browsers, the top-level object is window, but Nodes and Web workers don’t have Windows.
  • In browsers and Web workers, self also points to the top-level object, but Node has no self.
  • In Node, the top-level object is global, which is not supported in any other environment

In order to achieve the top-level object in different environments, the following ternary expression method can be used to achieve.

Typeof window! == 'undefined' ? window : (typeof process === 'object' && typeof require === 'function' && typeof global === 'object') ? global : this); Var getGlobal = function () {if (typeof self! == 'undefined') { return self; } if (typeof window ! == 'undefined') { return window; } if (typeof global ! == 'undefined') { return global; } throw new Error('unable to locate global object'); };Copy the code

But this way is relatively troublesome and complicated.es2020Introduce globalThis as a top layer that exists in any environment.

Reference links:

  • es6.ruanyifeng.com/
  • Tc39. Es/ecma262 / # se…
  • Zhuanlan.zhihu.com/p/152245696…