[ES2021] new features in ES12 - logical assignment operator, number separator, Promise.any, String.prototype.replaceAl, WeakRefsl

Keywords: Javascript Front-end

There are five new features:

  • Logical assignment operator??? =&&= And||=
  • Number separator_
  • Promise.any & AggregateError
  • String.prototype.replaceAll
  • Weakrefs & finalizationregistry object

1. Logical assignment operator??? =&&= And||=

??= &&= And||=

a||=b;  // a=a||b;    Equivalent to: a = a? a : b
a&&=b; // a=a&&b;   Equivalent to: a = a? b : a
a??=b; //a=a??b ;  Equivalent to: a = (a = = null|a = = undefined)? b : a

2. Number separator

The numeric literal is allowed to contain discontinuities, To improve readability.

1_000_000_000           // decimal system
0b1000_1111;               // Binary
0xFF_AA_8D;               // Hexadecimal
1_000_000_000n;         // BigInt

let a = 1_1; // 11
let a = 1__1 // Error, only one underscore is allowed as a number separator
let a = 1_;  // Error, delimiter cannot be at the end 
let a = _1;  // Error, the delimiter cannot be in the header 

Number(1_1); // 11
Number('1_1'); // NaN

Note: the separator cannot be in the tail and head, but only between numbers. Only one underscore is allowed as a number separator and cannot be continuous. The delimiter does not affect the type conversion value of the value, nor can it be recognized when the string is converted to a value.

3. Promise.any & AggregateError

Promise.any: the promise.any method accepts the promise array as a parameter and returns the synthesized promise.
As long as one promise in a given iteration is successful, the successful promise will be returned;
If no promise in the iteratable object is successful, an instance of failed promise and aggregateerror (a subclass of error) will be returned to collect single errors.

const promises = [
  fetch('/endpoint-a').then(() => 'a'),
  fetch('/endpoint-b').then(() => 'b'),
  fetch('/endpoint-c').then(() => 'c'),
];
try {
  const first = await Promise.any(promises);
  // Any of the promises was fulfilled.
  console.log(first);
  // → e.g. 'b'
} catch (error) {
  // All of the promises were rejected.
  console.assert(error instanceof AggregateError);
  // Log the rejection values:
  console.log(error.errors);
  // → [
  //     <TypeError: Failed to fetch /endpoint-a>,
  //     <TypeError: Failed to fetch /endpoint-b>,
  //     <TypeError: Failed to fetch /endpoint-c>
  //   ]
}

Promise.any is similar to Promise.all and Promise.race, but different from them:

  • Promise.all a failure is a failure, and success is also a failure
  • Promise.any success is success, and failure is success
  • Promise.race who is quick is who. No matter success or failure, the first result is the final result. Can handle timeout

4. String.prototype.replaceAll

Compared with String.prototype.replace, if you do not use global regular expressions, you cannot replace all instances of substrings in the string, and only the characters that match for the first time will be replaced.
String.prototype.replaceAll will replace all matching characters, so that simple global replacement does not rely strongly on regularity

'hello world'.replace('o', '_'); // hell_ world
'hello world'.replace(/o/g, '_'); // hell_ w_rld
'hello world'.replaceAll('o', '_'); // hell_ w_rld 

5. Weakrefs & finalizationregistry object

Generally speaking, in JavaScript, the reference of an object is strongly referenced, which means that as long as the reference of the object is held, it will not be garbage collected. Only when the object does not have any strong references, the js engine garbage collector will destroy the object and reclaim the memory space occupied by the object.

let obj = {a:1, b:2}; // As long as we access the obj object, the object will not be garbage collected

The WeakRef object allows you to create a weak reference to another object. A weak reference to an object means that it will not prevent the garbage collector from collecting when the object should be collected by the js engine garbage collector.
The Weakref instance has a method deref, which returns the referenced original object. If the original object has been collected, it returns the undefined object.

const ref = new WeakRef({ name: 'daotin' });
let obj = ref.deref();
if (obj) {
  console.log(obj.name); // daotin
} 

Note: using them correctly requires careful consideration. If possible, it is best to avoid using ` WeakRefs.

Using the FinalizationRegistry object, you can execute callback functions when the garbage collector collects objects.

// Build a callback where the listening object is cleared by the garbage collector
const registry = new FinalizationRegistry(heldValue => {
      console.log('----', heldValue);
});

const obj = {};
const token = {};

// Register listening
/********
 * register The parameters are:
 * obj1: Object to listen on
 * func: Parameters to execute callback function
 * obj2: Identifier for canceling listening
 * */
registry.register(obj, "obj deleted!", token);

// Cancel listening
registry.unregister(token);

// The callback may execute after a long time
// ---- obj deleted!

Posted by DwarV on Mon, 22 Nov 2021 14:09:52 -0800