I use it the most

ES6 features are some of the most used, including classes, modularity, arrow functions, function parameter defaults, template strings, destructively assigned values, extended operators, promises, lets, and const

In addition:

  • The ES7Array.prototype.includes()
  • ES8 async/await, String padding:padStart()andpadEnd()Object.values()
  • ES9’s Rest/Spread property, for await of,Promise.finally()
  • The ES10Array.prototype.flat()Array.prototype.flatMap()And the StringtrimStart() trimEnd()
  • The ES11Promise.allSettled, null value processing and optional chain
  • ES12’s logical assignment operators, numeric separators,Promise.any()

The most useful

ES6 features are very useful. In ES7-ES11, I am interested in:

  • ES8 async/await
  • ES9 for await of
  • The ES11Promise.allSettledAnd ES9Promise.finally()And ES12Promise.any()
  • There are also common logic operations: logical assignment operators, number separators, null-value handling, and optional chains, all of which optimize our code with great brevity

AllSettled, for await of asynchronous serial, promise.allsettled solves the promise.all problem, which will throw an error if one request fails. When we send multiple requests at once, all results will be returned. Whether success or failure, etc., etc., don’t know can look down

Here’s a list of all the features to fill in the gaps

ES6 (ES2015)

  • class
  • modular
  • Arrow function
  • Function parameter default value
  • Template string
  • Deconstruction assignment
  • Extension operator
  • Short for object property
  • Promise
  • Let the const

Specific no longer redundant introduction, this belongs to the front-end foundation

ES7 (ES2016)

  • Array.prototype.includes()

  • Exponential operator

Array.prototype.includes()

[1.2].includes(1) // true
Copy the code

Exponential operator

2支那5 / / 32
Copy the code

ES8 (ES2017)

  • async/await
  • Object.values()
  • Object.entries()
  • String padding: padStart()andpadEnd(), the padding string reaches the current length
  • Object.getOwnPropertyDescriptors()
  • A comma is allowed at the end of a function argument list
  • SharedArrayBuffer object
  • Atomics object

async/await

Asynchronous ultimate solution

async getInfo(){
    const res = await api.getData()
    // ... 
}
Copy the code

Object.values()

Object.values({a: 1.b: 2.c: 3}) 
/ / [1, 2, 3]
Copy the code

Object.entries()

Object.values({a: 1.b: 2.c: 3}) 
// [["a", 1], ["b", 2], ["c", 3]]
Copy the code

String padding: padStart()andpadEnd()

The padStart() method populates the current string with another string (repeated multiple times if necessary) so that the resulting string reaches the given length. Starts from the left side of the current string

// padStart
'sister'.padStart(7.'0') // "0sister"
// padEnd
'sister'.padEnd(7.'0') // "sister0"
Copy the code

Object.getOwnPropertyDescriptors()

Object. GetOwnPropertyDescriptors () function is used to retrieve an Object of all their property descriptors, if you don’t have any own properties, it returns null objects

A comma is allowed at the end of a function argument list

This is a painless update designed to make it easier to modify the same function for collaborative development with Git and reduce unnecessary line changes

ES9 (ES2018)

  • Asynchronous iteration (for await of)
  • Promise.finally()
  • Rest/Spread properties
  • New regular expression features
    • Regular expression reverse assertion (lookbehind)
    • Regular expression dotAll mode
    • Regular Expression Named Capture Groups
    • Regular expression Unicode escape
    • The template string for a non-escape sequence

Asynchronous iteration (for await of)

Await can be used with for… The of loop is used together to run asynchronous operations in a serial fashion

async function getInfos(arr) {
  for await (let i of arr) {
    getData(i)
  }
}
Copy the code

Promise.finally()

Finally runs whether the Promise runs successfully or fails

function getInfos() {
  getData1()
  .then(getData2)
  .catch(err= > {
    console.log(err);
  })
  .finally(() = > {
    // ...
  });
}
Copy the code

Rest/Spread properties

const values = [1.2.3]
console.log( Math.min(... values) )/ / 1
Copy the code

New regular expression features

Regular Expression Named Capture Groups

In some regular expression patterns, matching with numbers can be confusing. For example, use the regular expression /(\d{4})-(\d{2})-(\d{2})/ to match dates. Because American and British date representations are different, it can be difficult to tell which group represents the date and which represents the month

const re = /(\d{4})-(\d{2})-(\d{2})/;
const match= re.exec('2019-01-01');
console.log(match[0]);    / / - 2019-01-01
console.log(match[1]);    / / - 2019
console.log(match[2]);    / / - 01
console.log(match[3]);    / / - 01
Copy the code

ES9 introduces named capture groups, which allow you to assign a name to each group match, making it both easy to read code and easy to reference.

const re = / (? 
      
       \d{4})-(? 
       
        \d{2})-(? 
        
         \d{2})/
        
       
      ;
const match = re.exec('2019-01-01');
console.log(match.groups);          // → {year: "2019", month: "01", day: "01"}
console.log(match.groups.year);     / / - 2019
console.log(match.groups.month);    / / - 01
console.log(match.groups.day);      / / - 01
Copy the code

Regular expression reverse assertion (lookbehind)

let test = 'hello sisteran'
console.log(test.match(/ (? <=sisteran\s)hello/))
// ["hello", index: 6, input: "sisteran hello", groups: undefined]
Copy the code

Regular expression dotAll mode

In a regular expression, the point (.) Is a special character that represents any single character, with two exceptions. One is a four-byte UTF-16 character, which can be solved with the U modifier; The other is a line terminator, such as a newline (\n) or carriage return (\r), which can be added to the regular expression by the S (dotAll)flag of ES9:

console.log(/foo.bar/.test('foo\nbar')) // false
console.log(/foo.bar/s.test('foo\nbar')) // true
Copy the code

How do you tell if the current re is using dotAll?

const re = /foo.bar/s // Or, `const re = new RegExp('foo.bar', 's'); `.
console.log(re.test('foo\nbar')) // true
console.log(re.dotAll) // true
console.log(re.flags) // 's' 
Copy the code

Regular expression Unicode escape

A new class notation \p{… } and \ {P… }, which allows a regular expression to match all characters that match a Unicode attribute

The template string for a non-escape sequence

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.

ES10 (ES2019)

  • Added Arrayflat()Methods andflatMap()methods
  • Added StringtrimStart()Methods andtrimEnd()methods
  • Object.fromEntries()
  • Symbol.prototype.description()
  • Function.prototype.toString()Now return exact characters, including Spaces and comments
  • To simplify thetry {} catch {}, modifycatchThe binding

Added Arrayflat()Methods andflatMap()methods

Flat () and flatMap() are essentially reduce and concat operations

[1.2[3.4]].flat(Infinity); // [1, 2, 3, 4]

[1.2.3.4].flatMap(a= > [a**2]); // [1, 4, 9, 16]
Copy the code

Added StringtrimStart()Methods andtrimEnd()methods

Remove whitespace at the beginning and end of the string, respectively

Object.fromEntries()

Returns an array of key-value pairs for the given object’s own enumerable properties

Object.fromentries () is the reverse of Object.entries()

  • FromEntries converts a Map to an Object:
const map = new Map([['foo'.'bar'], ['baz'.42]]);const obj = Object.fromEntries(map);
console.log(obj); // { foo: "bar", baz: 42 }
Copy the code
  • FromEntries converts Array to Object:
const arr = [ ['0'.'a'], ['1'.'b'], ['2'.'c']].const obj = Object.fromEntries(arr);
console.log(obj); // { 0: "a", 1: "b", 2: "c" }
Copy the code

Symbol.prototype.description()

Read-only property, a string that returns the optional description of the Symbol object.

Symbol('description').description; // 'description'
Copy the code

Function.prototype.toString()Now return exact characters, including Spaces and comments

function/ *comment* /foo/ *another comment* /) {}

// Comments will not be printed before
console.log(foo.toString()); // function foo(){}

// ES2019 prints comments together
console.log(foo.toString()); // function /* comment */ foo /* another comment */ (){}

// Arrow function
const bar /* comment */ = /* another comment */ () = > {};

console.log(bar.toString()); / / () = > {}
Copy the code

To simplify thetry {} catch {}, modifycatchThe binding

try {} catch(e) {}
Copy the code

Now it is

try {} catch {}
Copy the code

ES11 (ES2020)

  • Promise.allSettled()
  • Optional chaining
  • Coalescing Operator (Nullish coalescing Operator)
  • import()
  • globalThis
  • BigInt
  • String.prototype.matchAll

Promise.allSettled

Unlike promise.all, it returns all Promise results

const promise1 = Promise.resolve('hello')
const promise2 = new Promise((resolve, reject) = > setTimeout(reject, 200.'problem'))

Promise.allSettled([promise1, promise2])
    .then((values) = > {
        console.log(values)
    })
Copy the code

Optional chaining

Optional chains allow us to query multi-tiered objects without the need for redundant pre-validation.

var name = user && user.info && user.info.name;
Copy the code

Or this

var age = user && user.info && user.info.getAge && user.info.getAge();
Copy the code

Uncaught TypeError: Cannot read property… TypeError: Cannot read property…

With Optional Chaining, the above code becomes

varname = user? .info?.name;Copy the code
varage = user? .info?.getAge?.();Copy the code

Coalescing Operator (Nullish coalescing Operator)

Set a default value

var level =  user.data.level || 'No level yet';
Copy the code

Let’s see what happens with the null-value merge operator. Okay

/ / {
// "level": 0
// }
var level = user.level ?? 'No level yet'; // level -> 0


/ / {
// "an_other_field": 0
// }
var level = user.level ?? 'No level yet'; // level -> 'level'

Copy the code

import()

According to the need to load

globalThis

The purpose of globalThis is to provide a standardized way to access global objects. With globalThis, you can access global objects in any context at any time

BigInt

BigInt is a built-in object that provides a way to represent integers greater than 253-1. This was originally the largest Number that could be represented as Number in Javascript. BigInt can represent an arbitrarily large integer

String.prototype.matchAll()

The matchAll() method returns an iterator containing all matched regular expressions and grouped capture results

ES12 (ES2021)

  • String.prototype.replaceAll()
  • Promise.any()
  • WeakRef
  • Logical Assignment Operators
  • Numeric separators (Numeric Separators)

String.prototype.replaceAll()

Returns a brand new string, with all characters matching the rules replaced

const str = 'sisteran';
str.replaceAll('s'.'q'); // 'qiqteran'
Copy the code

Promise.any()

Promise.any() receives a Promise iterable (such as an array),

  • If one of the promises succeeds, the promise that succeeded is returned
  • If none of the iterable promises succeeds (i.e. all promises fail/reject), return a failed promise

WeakRef

WeakRefs Class creates a weak reference to an object (a weak reference to an object means that it does not prevent the GC from collecting when the object should be collected by the GC)

Logical Assignment Operators

a ||= b
/ / equivalent to the
a = a || (a = b)

a &&= b
/ / equivalent to thea = a && (a = b) a ?? = b/ / equivalent to the
a = a ?? (a = b)
Copy the code

Numeric separators (Numeric Separators)

const money = 1 _000_000_000 / / 1000000000
Copy the code

Reference:

  • Grass ES2020 new features
  • New features of ES6, ES7, ES8, ES9, and ES10
  • New features of ES7, ES8, ES9, and ES10

Three minutes a day