Click to jump to my personal blog for past posts

preface

On March 13, 2021, ES2021 candidate proposals released a version of their final feature set. If it is approved at the ECMA conference in June, it will become an official standard!

The candidate proposal mentions the following new features in ECMAScript:

  • String.prototype.replaceAll()
  • Promise.any
  • Logical operators and assignment expressions
  • Numeric separator
  • WeakRef and Finalizers

These new features are now in their fourth phase and have been added to Google Chrome V8. Let’s take a look at some of the new ES2021 features.

String.prototype.replaceAll()

const newString = oldString.replaceAll(pattern, replacement);
Copy the code

This method returns a new string, and all patterns are passed to its replacement. Where the pattern argument can be a string or regular expression, and the replacement argument can be a string or a function executed for each match.

The replaceAll method is a sequel to the string. replace method, which only replaces where pattern was first found.

const str = "Linda is a self-taught developer.Linda will rule the world";

let newStr = str.replace("Linda"."Micheal")
//output: Micheal is a self-taught developer.Linda will rule the world

let newStr = str.replaceAll("Linda"."Micheal")
//output: Micheal is a self-taught developer.Micheal will rule the world

Copy the code

In the past, if you need to replace all the matches, you have to write a regular expression to make a full replacement.

const str = "hello world, hello code";
const newStr = str.replace(/hello/g."hi");
console.log(newStr); // "hi world, hi code"
Copy the code

Now have a String. The prototype. The replaceAll () even if the input String can completely replace matches.

const str = "hello world, hello code";
const newStr = str.replaceAll("hello"."hi");
console.log(newStr); // "hi world, hi code"
Copy the code

Promise.any

Introduced in ES6Promise.race()Promise.all() Methods, ES2020 addedPromise.allSettled(). ES2021 adds another enablePromiseEasier ways to deal with:Promise.any()

Promise.any() receives a Promise iterable and returns the successful Promise as long as one of the promises succeeds (as shown in example 1). If none of the promises in the iterable succeeds (that is, all promises fail/reject), an instance of the failed promise and AggregateError type (as shown in example 2) is returned, which is a subclass of Error. Used to group together a single error.

Promise.any() is similar to the promise.race () method, except that it doesn’t end if a Promise goes into the rejected state.

/ / sample 1
Promise.any([
  new Promise((resolve, reject) = > setTimeout(reject, 200.'Third')),
  new Promise((resolve, reject) = > setTimeout(resolve, 1000.'Second')),
  new Promise((resolve, reject) = > setTimeout(resolve, 2000.'First')),
])
.then(value= > console.log(`Result1: ${value}`))
.catch (err= > console.log(err))

Promise.race([
  new Promise((resolve, reject) = > setTimeout(reject, 200.'Third')),
  new Promise((resolve, reject) = > setTimeout(resolve, 1000.'Second')),
  new Promise((resolve, reject) = > setTimeout(resolve, 2000.'First')),
])
.then(value= > console.log(`Result2: ${value}`))
.catch (err= > console.log(err))

/**** Output ****/
// Third
// Result1: Second
Copy the code

In the above code, the promise.any () method’s argument array contains three Promise operations. This will be fulfilled as long as one of them becomes fulfilled, the Promise object returned by promise.any () will become fulfilled, and the result returned by promise.race ([p1, p2, p3]) which is faster will be returned. Whether the result itself is a success state or a failure state.

This will be fulfilled someday. If no promise is fulfilled, promise.any () returns an AggregateError.

/ / sample 2
const pErr1 = new Promise((resolve, reject) = > {
  reject('Always fail 1');
});
const pErr2 = new Promise((resolve, reject) = > {
  reject('Always fail 2');
});
Promise.any([pErr1,pErr2]).catch((err) = > {
  console.log(err);
})

/**** Output ****/
// "AggregateError: All promises were rejected"
Copy the code

Logical operators and assignment expression (&&, | | =,?? =)

There are many assignment operators and logical operators in JavaScript, such as the following basic example:

// Assignment Operator Example
let num = 5
num+=10
console.log(num) / / 15
// Logical Operator Example
let num1 = 6
let num2 = 3
console.log(num1 === 6 && num2 === 2) // false
console.log(num1 === 6 || num2 === 2) // true
Copy the code

The new proposal allows us to combine the logical operator with the assignment operator

1. Logical assignment operator with && operator

var x = 1;
var y = 2;
x &&= y;
console.log(x); / / 2
Copy the code

The operation in line 3 is equivalent to: x && (x = y) or equivalent to

if(x) {
  x = y
}
Copy the code

Since x is a true value, we assign the value y, which is 2. In short, the operator &&= assigns the RHS variable value to the LHS variable only if the LHS value is true.

2, with the | | operator logic assignment operator

The RHS variable value is assigned to the LHS variable only if the LHS value is false.

// Logical Assignment Operator with || operator
let num1
let num2 = 10
num1 ||= num2
console.log(num1) / / 10
// Line 4 can also be written as following ways
// 1. num1 || (num1 = num2)
// 2. if (! num1) num1 = num2
Copy the code

3, with?? The logical assignment operator for the

ES2020 introduces the null-merge operator, which can also be used in combination with the assignment operator. The value of the RHS variable is assigned to the LHS variable only if LHS is undefined or only NULL.

// Logical Assignment Operator with ?? operator
let num1
let num2 = 10num1 ?? = num2console.log(num1) / / 10
num1 = falsenum1 ?? = num2console.log(num1) // false
// Line 4 can also be written as following ways
// num1 ?? (num1 = num2)
Copy the code

Numeric separator

We will make it easier to read values and improve readability by using the _ (underscore) character to provide separation between groups of numbers.

let x = 100 _000; / / 100000
Copy the code

The numeric separator also works with BigInt numbers.

const trillion = 1000_000_000_000n;
console.log(trillion.toString()); / / "1000000000000"
Copy the code

The delimiter is for readability purposes only. Therefore, it can be placed anywhere in the number.

const amount = 178 _00;
console.log(amount.toString()); / / "17800"
Copy the code

WeakRef and Finalizers

This feature includes two advanced objects, WeakRef and FinalizationRegistry. Depending on usage, these interfaces can be used alone or together. ** The official recommendation is not to use WeakRef and finalizer easily. ** One reason is that they can be unpredictable, and another is that they don’t really help the GC do its job and may actually make garbage collection more difficult.

In JavaScript, when you create a reference to creating an object, the reference prevents the object from being garbage collected, meaning that JavaScript cannot delete the object and free its memory. You can make an object exist forever as long as the reference to it always exists.

ES2021 has a new class WeakRefs. Allows creation of weak references to objects. This enables existing objects to be traced without preventing them from being garbage collected. Useful for caching and object mapping.

You must create a new WeakRef with the new keyword and put some objects in parentheses as parameters. When you want to read a reference (the object being referenced), you do so by calling deref() on a weak reference.

const myWeakRef = new WeakRef({
  name: 'stars'.year: '25'
})

myWeakRef.deref()
// => {name: 'xingye ', year: '25'}

myWeakRef.deref().name
// => < span style = "box-sizing: border-box; color: RGB (255, 255, 255);
Copy the code

Closely linked to WeakRef is another feature called Finalizers or FinalizationRegistry. This function allows you to register a callback function that will be called when the object is garbage collected.

/ / create FinalizationRegistry:
const reg = new FinalizationRegistry((val) = > {
  console.log(val)
})

(() = > {
  // Create a new object:
  const obj = {}

  // Register finalizer for the obj object:
  // The first argument is the object for which finalizer is registered.
  // Second argument: the value of the callback function defined above.
  reg.register(obj, 'obj has been garbage-collected.')
})()
// Output when "obj" is garbage collected:
// 'obj has been garbage-collected.'
Copy the code

Refer to the article

  • ES2021 / ES12 New Features
  • Everything new coming in ES2021
  • JavaScript ES2021 Exciting Features
  • What interesting features are in the upcoming ES2021 (ES12)