Hi, I’m Daotin, the front end team leader. If you want to learn more about the front end, follow me and unlock the new front end growth posture.
The following text:
On June 22, 2021, the 121st Ecma International Conference was held via teleconference. With the adoption of the ES2021 standard, ECMAScript 2021 (ES12) becomes the de facto ECMAScript standard.
This article gives you an overview of what syntax has been added to JavaScript this year, but not a lot.
There are five new features:
- Logical assignment operator
- Numeric separator
- Promise.any & AggregateError
- String.prototype.replaceAll
- WeakRefs & FinalizationRegistry objects
Logical assignment operator
?? = && and | | =
?? = and?? Returns an rvalue if the lvalue is null or undefined, otherwise returns an lvalue.
The difference is…? = contains operations that assign to the left value. Analogous to the equals sign in += -=.
/ / the old
let a = null;
a = a ?? 'daotin';
a = a && 'daotin';
a = a || 'daotin';
/ / new
let a = null; a ?? ='daotin';
a &&= 'daotin';
a ||= 'daotin';
Copy the code
Numeric separator
Allow numeric literals to contain discontinuous _ in the middle to improve readability.
1 _000_000_000 // Ah, so a billion
101 _475_938. 38 // And this is hundreds of millions
let a = 1 _1; / / 11
let a = 1__1 // Error, only an underscore is allowed as a number separator
let a = 1_; // Error, the delimiter cannot be at the end
let a = _1; // Error, the separator cannot be in the header
Number(1 _1); / / 11
Number('1 _1'); // NaN
Copy the code
Note: the separator cannot be in the tail and the head, and the ** can only be between digits. Only one underscore is allowed as the number separator, which is not consecutive. The ** delimiter does not affect the type conversion value of a value, nor is it recognized when a string is converted to a value.
Promise.any & AggregateError
Promise.any method: Any takes an array of promises as arguments and returns a synthesized Promise. Whenever a promise in a given iteration succeeds, the value of the first promise is taken as its return value,
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);
/ / - > [
//
,
//
,
//
/ /]
}
Copy the code
This code example checks which endpoint is the most responsive and then logs it. Only when all requests fail do we end up in the code catch block, where we handle the error.
Multiple Promise instances wrapped into a new Promise instance:
The name of the | describe |
---|---|
all | If a Promise fails, the failure is returned immediately, and the success array is returned for all successes |
race | The ace is a game, a contest. Returns the result as soon as a Promise completes (whether it succeeds or fails) |
any | If one Promise succeeds, it returns success immediately, and if all promises fail, AggregateError is returned |
allSettled | All promises are returned after completion (whether successful or unsuccessful), and an array of results is returned |
String.prototype.replaceAll
In contrast to string.prototype. replace, you cannot replace all instances of substrings in a String without using a global regular expression. Only the first matching character is replaced.
'hello world'.replace('o'.'_'); // hell_ world
'hello world'.replace(/o/g.'_'); // hell_ w_rld
'hello world'.replaceAll('o'.'_'); // hell_ w_rld
Copy the code
WeakRefs & FinalizationRegistry objects
In general, in JavaScript, a reference to an object is strongly referential, which means that as long as a reference to an object is held, it is not garbage collected. Only if the object does not have any strong references will the JS engine garbage collector destroy the object and reclaim the memory occupied by the object.
let obj = {a:1.b:2}; // As long as we access the obj object, it is not garbage collected
Copy the code
WeakRefs, however, can create a weak reference. Weak reference of an object means that it does not prevent the garbage collector from collecting when the object should be collected by the JS engine garbage collector.
A Weakref instance has a method, deref, that returns the referenced original object or undefined object if the original object has been collected.
const ref = new WeakRef({ name: 'daotin' });
let obj = ref.deref();
if (obj) {
console.log(obj.name); // daotin
}
Copy the code
Note: Their proper use requires careful consideration and is best avoided if possible.
You use FinalizationRegistry objects to perform callback functions when the garbage collector collects the object.
// Build the callback that the listener is cleared by the garbage collector
const registry = new FinalizationRegistry(heldValue= > {
console.log(The '-', heldValue);
});
const obj = {};
const token = {};
// Register listener
registry.register(obj, "obj deleted!", token);
// Cancel the listener
registry.unregister(token);
// The callback may be executed much later
// ---- obj deleted!
Copy the code
Register parameters are:
- Object to listen on
- Arguments to execute the callback function
- Cancel the identifier used for listening
Reference links:
-
h3manth.com/ES2021
-
Juejin. Cn/post / 697851…
-
Mp.weixin.qq.com/s/pRkTLu6mo…
— End —
Hi, I am Daotin, front end team leader, focusing on sharing front end and cognition. I hope to share my front-end learning and working experience with you here and record my personal growth.
For more front-end highlights, follow me and unlock new front-end growth poses.
Above, if you think it is helpful to you, click on the praise, so that the captain also has the motivation to update, thank everyone old folks ~~~ I heard that people like to click on the praise, there will be good luck within a month