[JavaScript] ES7 (ECMAScript 2016) to ES9 (ECMAScript 2018) summary

ES7(ECMAScript 2016)

1.Array.prototype.includes()

The array includes() method is used to determine whether an array contains a specified value. If it does, it returns true; otherwise, it returns false. The includes function is similar to the indexOf function

list.includes(x) === list.indexOf(x) >= 0

2. Exponential operator**

The exponential operator * * is introduced in ES7, and * * has the calculation result equivalent to Math.pow(...).

console.log(2**10);// Output 1024 to the tenth power of 2

ES8(ECMAScript 2017)

1.async/await: the ultimate asynchronous solution

async/await can be said to be the syntax sugar of co module and generator function. Solve js asynchronous code with clearer semantics to make asynchronous code look like synchronous code.

async fetchData(query) =>{  
  try {      
    const response = await axios.get(`/query?query=${query}`); 
    const data = response.data;     
    return data;    
 }catch (error)    {      
   console.log(error)   
 }} 
fetchData(query).then(data =>{    
     this.processfetchedData(data)
})

2.Object.values()

Object.values() is a new function similar to Object.keys(), but returns all values of the object's own properties, excluding inherited values.

const obj = {a: 1, b: 2, c: 3};
// ES7
const vals=Object.keys(obj).map(key=>obj[key]);
console.log(vals);//[1, 2, 3]
// ES8
const values=Object.values(obj1);
console.log(values);//[1, 2, 3]

3.Object.entries()

The Object.entries() function returns an array of key value pairs of enumerable properties of a given object.

// ES7
Object.keys(obj).forEach(key=>{
    console.log('key:'+key+' value:'+obj[key]);
})
// ES8
for(let [key,value] of Object.entries(obj1)){
    console.log(`key: ${key} value:${value}`)
}

4.String padding

Allows you to add an empty string or other string to the beginning or end of the original string

String.prototype.padStart

String.padStart(targetLength,[padString])

console.log('0.0'.padStart(4,'10')) //10.0
console.log('0.0'.padStart(20))// 0.00   

String.prototype.padEnd

String.padEnd(targetLength,padString])
console.log('0.0'.padEnd(4,'0')) //0.00    
console.log('0.0'.padEnd(10,'0'))//0.00000000

targetLength: the target length that the current string needs to be filled in. If this value is less than the length of the current string, the current string itself is returned.
padString: (optional) fill string. If the string is too long and the length of the filled string exceeds the target length, only the leftmost part will be reserved, and other parts will be truncated. The default value of this parameter is "";

5. Comma is allowed at the end of function parameter list

It is convenient to modify the same function when using git for multi person collaborative development to reduce unnecessary line changes

6.Object.getOwnPropertyDescriptors()

Gets the descriptor of all self attributes of an object. If there are no self attributes, an empty object is returned

7.SharedArrayBuffer object

Used to represent a general, fixed length raw binary data buffer

8.Atomics object

Provides a set of static methods to perform atomic operations on SharedArrayBuffer objects

ES9(ECMAScript 2018)

1. Asynchronous iteration

ES2018 introduces asynchronous iterators. await can be used with for... of loops to run asynchronous operations in a serial manner

Five ways to use async/await in a loop
Two forms:

  1. It means that all asynchronous requests are executed only by means of a loop, and the order is not guaranteed. We call it "parallel" for short
  2. It means that each asynchronous request in the loop is executed in order. We call it "serial" for short

Parallel loop method:
Array.forEach,Promise.all
Serial loop method:
for...of...,reduce,generator

  • generator
//Function * keyword can define a generator function inside an expression.
async function* generateSequence(items) {
for (const i of items) {
  await new Promise(resolve => setTimeout(resolve, i));
  yield i;
}
}

(async () => {
let generator = generateSequence(['3000','8000','1000','4000']);
for await (let value of generator) {
  console.log(value);
}
})();

2. Promise.finally()

A Promise call chain either successfully reaches the last. then() or fails to trigger. catch(). In some cases, you want to run the same code whether 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(() => {
    // finish here!
  });
}

3. Rest / spread (extended operator) attribute

Rest parameter and spread extension operator have been introduced in ES6, but ES6 is only for arrays.
In ES9, rest parameters and extension operators like arrays are provided for objects

Rest parameter

  • es6 (array only)

    The residual parameter syntax allows us to represent an indefinite 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]
    }
    
  • es9 (applied to objects)
    Like arrays, Rest parameters can only be used at the end of a declaration. In addition, it only applies to the top level of each object, and it cannot be applied if objects are nested in objects.
    	const myObject = {
    	  a: 1,
    	  b: 2,
    	  c: 3
    	};
    	const { a, ...x } = myObject;
    	// a = 1
    	// x = { b: 2, c: 3 }
    	
    	// Or you can use it to pass parameters to a function
    	restParam({
    	  a: 1,
    	  b: 2,
    	  c: 3
    	});
    	
    	function restParam({ a, ...x }) {
    	  // a = 1
    	  // x = { b: 2, c: 3 }
    	}
    

Expand operator

The same as the inverse operation of Rest parameter. The expansion operator works the opposite way, converting an array into a separate argument that can be passed to a function. For example, Math.max() returns the maximum value in a given number

  • es6 (array only)
    const values = [99, 100, -1, 48, 16];
    console.log( Math.max(...values) ); // 100
    
  • es9 (applied to objects)
    You can use the extension operator to copy an object, such as obj2 = {... obj1}, but this is only a shallow copy of the object. Extension operators can be used within other objects, for example:
    const obj1 = { a: 1, b: 2, c: 3 };
    const obj2 = { ...obj1, z: 26 };
    // obj2 is { a: 1, b: 2, c: 3, z: 26 }
    

Regular part, need to review, first summarize the general meaning

Regular expression named capture group

before

JavaScript regular expressions can return a matching object -- an array of classes containing matching strings

For example: resolve the date in the format of YYYY-MM-DD:

es9

The code is difficult to read, and changing the structure of regular expressions may change the index of matching objects. ES2018 allows named capture groups to use symbols< Name >, named immediately after opening the capture bracket * * (* * as shown in the following example:

const reDate = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/,
  match  = reDate.exec('2018-04-30'),
  year   = match.groups.year,  // 2018
  month  = match.groups.month, // 04
  day    = match.groups.day;   // 30
  • Any named group that fails to match will return undefined
  • Named capture can also be used in the replace() method. For example, convert the date to the American MM-DD-YYYY format:

Regular expression reverse assertion (lookbehind)

Regular expression dotAll mode

Match any single character except carriage return in the regular expression, mark s to change this behavior and allow the occurrence of line terminator, for example:

Regular expression Unicode escape

So far, local access to Unicode character attributes in regular expressions is not allowed. ES2018 adds Unicode attribute escape in the form of \ p {...} and \ p {...}. The tag u (unicode) is used in regular expressions. In the \ p block, the attributes to be matched can be set in the form of key value pairs instead of specific contents. For example:


This feature can avoid using specific Unicode intervals for content type judgment and improve readability and maintainability.

Template string for non escape sequence

ES2018 removes syntax restrictions on ECMAScript escaping sequences in tagged template strings.
Before, \ u starts a unicode escape, \ x starts a hexadecimal escape, and \ followed by a number starts an octal escape. This makes it impossible to create a specific string, such as the Windows file path C:\uuu\xxx1.

Keywords: Javascript Front-end

Added by Toy on Fri, 19 Nov 2021 05:24:07 +0200