Original link: www.sitepoint.com/es2018-what…

In this article, I’ll introduce the new features of ES2018 (ES9) and show you how to use them.

JavaScript (ECMAScript) is an evolving standard implemented by many vendors across multiple platforms. ES6 (ECMAScript 2015) took six years to hammer out and is a big release. A new annual release process was developed to simplify the process and add features faster. ES9 (ES2018) is the latest version as of this writing.

TC39 is made up of parties, including browser vendors, who meet to push JavaScript proposals along a rigorous development path:

  • Stage 0: strawman — The submission of the original idea.
  • Stage 1: Proposal — A formal proposal document initiated by at least one TC39 member that includes API examples.
  • Stage 2: Draft — An initial version of the functional specification that contains two experimental implementations of the functional specification.
  • Stage 3: Candidate — The proposal specification is reviewed and receives feedback from vendors
  • Stage 4: Finished — The proposal is ready for ECMAScript, but it may take longer to get to the browser or Nodejs

ES2016

ES2016 adds two small features to illustrate the standardization process:

  1. An array ofincludes()Method that checks whether an array contains a specified value and returns if it does, depending on the casetrueOtherwise returnfalse.
  2. a ** bThe exponent operator, which is associated withMath.pow(a, b)The same.

ES2017

ES2017 offers more new features:

  1. Async functions render clearer Promise syntax
  2. Object.valuesMethod returns an array of all the enumerable property values of a given object, the order and use of the valuesfor... inThe order of the cycles is the samefor... inLoop through properties in the prototype chain.
  3. Object.entries()Method returns an array of key-value pairs for a given object’s own enumerable properties, arranged and usedfor... inThe same order is returned when iterating over the changed objectsfor... inLoops also enumerate properties in the stereotype chain.
  4. Object.getOwnPropertyDescriptors()Returns a descriptor for all of an object’s own properties..value..writable..get..set..configurable.enumerable)
  5. padStart()andpadEnd(), the padding string reaches the current length
  6. Closing comma, array definition, and function argument list
  7. ShareArrayBufferandAtomicsUsed for reading and writing from a shared memory location

For more information about ES2017 see What’s New in ES2017

ES2018

ECMAScript 2018 (or ES9) is now available. The following features have reached Stage 4, but are not fully implemented in various browsers at the time of this writing.

Asynchronous iterative

At some point in async/await, you may try to call an asynchronous function in a synchronous loop. Such as:

async function process(array) {
  for (let i of array) {
    awaitdoSomething(i); }}Copy the code

This code will not work, nor will the following:

async function process(array) {
  array.forEach(async i => {
    await doSomething(i);
  });
}
Copy the code

In this code, the loop itself remains synchronized and is called before the internal asynchronous function is called.

ES2018 introduces asynchronous iterators, which are just like regular iterators, except that the next() method returns a Promise. So await can and for… The of loop is used together to run asynchronous operations in a serial fashion. Such as:

async function process(array) {
  for await (let i ofarray) { doSomething(i); }}Copy the code

Promise.finally()

A chain of Promise calls either succeeds in reaching the last.then() or fails to trigger.catch(). In some cases, you’ll want to run the same code whether a Promise runs successfully or fails, such as clearing, deleting conversations, closing database connections, etc.

.finally() allows you to specify the final logic:

function doSomething() {
  doSomething1()
  .then(doSomething2)
  .then(doSomething3)
  .catch(err= > {
    console.log(err);
  })
  .finally((a)= > {
    // finish here!
  });
}
Copy the code

Rest/Spread properties

ES2015 introduced Rest parameters and extended operators. Three points (…) Only for arrays. Rest parameter syntax allows us to represent a pudding number of parameters as an array.

restParam(1.2.3.4.5);

function restParam(p1, p2, ... p3) {
  // p1 = 1
  // p2 = 2
  // p3 = [3, 4, 5]
}
Copy the code

The expansion operator works in reverse, converting an array into a separate parameter that can be passed to a function. For example, math.max () returns the maximum value in a given number:

const values = [99.100.- 1.48.16];
console.log( Math.max(... values) );/ / 100
Copy the code

ES2018 provides the same Rest argument () and expansion operator for object deconstruction as arrays, a simple example:

const myObject = {
  a: 1.b: 2.c: 3
};

const{ a, ... x } = myObject;// a = 1
// x = { b: 2, c: 3 }
Copy the code

Or you can use it to pass arguments to functions:

restParam({
  a: 1.b: 2.c: 3
});

function restParam({ a, ... x }) {
  // a = 1
  // x = { b: 2, c: 3 }
}
Copy the code

Like arrays, Rest parameters can only be used at the end of a declaration. Furthermore, it only applies to the top layer of each object, not if there are nested objects in the object.

Extension operators can be used within other objects, for example:

const obj1 = { a: 1.b: 2.c: 3 };
constobj2 = { ... obj1,z: 26 };
// obj2 is { a: 1, b: 2, c: 3, z: 26 }
Copy the code

You can copy an object using the extension operator, such as obj2 = {… Obj1}, but this is just a shallow copy of the object. Also, if an attribute of object A is object B, then in the cloned object cloneB, that attribute points to object B.

Regular Expression Named Capture Groups

JavaScript regular expressions can return a matching object — an array of classes containing matching strings, such as: date parsing in YYYY-MM-DD format:

const
  reDate = / [0-9] {4}) - ([0-9] {2}) - ([0-9] {2}) /,
  match  = reDate.exec('2018-04-30'),
  year   = match[1]./ / 2018
  month  = match[2].// 04
  day    = match[3]; / / 30
Copy the code

Such code is difficult to read, and changing the structure of a regular expression can change the index of a matching object.

ES2018 allows named capture groups to use symbols?

, named immediately after opening the capture parentheses, as shown in the following example:

const
  reDate = / (? 
      
       [0-9]{4})-(? 
       
        [0-9]{2})-(? 
        
         [0-9]{2})/
        
       
      ,
  match  = reDate.exec('2018-04-30'),
  year   = match.groups.year,  / / 2018
  month  = match.groups.month, // 04
  day    = match.groups.day;   / / 30
Copy the code

Undefined is returned for any named group that fails to match.

Named capture can also be used in the replace() method. For example, convert dates to the US MM-DD-YYYY format:

const
  reDate = / (? 
      
       [0-9]{4})-(? 
       
        [0-9]{2})-(? 
        
         [0-9]{2})/
        
       
      ,
  d      = '2018-04-30',
  usDate = d.replace(reDate, '$<month>-$<day>-$<year>');
Copy the code

Regular expression reverse assertion (lookbehind)

JavaScript currently supports lookahead in regular expressions. This means that a match occurs, but there is no capture, and the assertion is not included in the entire match field. For example, capturing a currency symbol from a price:

const
  reLookahead = /\D(? =\d+)/,
  match       = reLookahead.exec('$123.89');

console.log( match[0]);/ / $
Copy the code

ES2018 introduced works in the same way but matches the previous lookbehind so I can ignore the currency symbol and simply capture the number of prices:

const
  reLookbehind = / (? <=\D)\d+/,
  match        = reLookbehind.exec('$123.89');

console.log( match[0]);/ / 123.89
Copy the code

The above is an affirmative reverse assertion, non-digit \D must exist. Also, there are negative reverse assertions, which indicate that a value must not exist, for example:

const
  reLookbehindNeg = / (? 
      ,
  match           = reLookbehind.exec('$123.89');

console.log( match[0]);// null
Copy the code

Regular expressiondotAllmodel

Regular expression midpoint. Matches any single character other than carriage return. The s tag changes this behavior by allowing line terminators, for example:

/hello.world/.test('hello\nworld');  // false
/hello.world/s.test('hello\nworld'); // true
Copy the code

Regular expression Unicode escape

Until now, native access to Unicode character attributes in regular expressions was not allowed. ES2018 has added Unicode attribute escapes of the form \p{… } and \ {P… }, use the flag U (Unicode) setting in regular expressions, and in the \p block, you can set the attributes to be matched in key-value pairs rather than the content. Such as:

const reGreekSymbol = /\p{Script=Greek}/u;
reGreekSymbol.test('PI.); // true
Copy the code

This feature improves readability and maintainability by eliminating the need for specific Unicode ranges for content type determination.

The template string for a non-escape sequence

Finally, ES2018 removes syntactic restrictions on ECMAScript escaping sequences in tagged template strings.

Previously, \u started a Unicode escape, \x started a hexadecimal escape, and \ followed by a number started an octal escape. This makes it impossible to create specific strings, such as the Windows file path C:\uuu\ XXX \111. Refer to template strings for more details.

These are all the new features for ES2018, ES2019 has already started, are there any features you’re looking forward to seeing next year?

Refer to the translator

  • Understanding of javascript re assertions
  • [RPU-A] Regular Unicode escape proposal into ES2018
  • Template string — ES2018 revision of illegal escape sequences
  • The template string for a non-escape sequence
  • Regular expressions name capture groups