Three Useful JavaScript Features in ECMAScript 2021
ECMAScript, the standardized specification for JavaScript, is continuously evolving to meet the demands of modern web development. With the release of ECMAScript 2021, developers can look forward to some innovative features that further enhance the language’s capabilities. This article will highlight the top 3 new features introduced in ECMAScript 2021 and provide examples of their usage.
1. Logical Assignment Operators
ECMAScript 2021 introduces three new logical assignment operators, which combine the concepts of logical operations and assignment. These new operators are:
&&=
||=
??=
The logical assignment operators simplify the code and improve its readability. Here’s how these new operators can be used.
The &&=
operator performs a logical AND operation and assigns the result back to the left operand if the left operand is truthy; otherwise, the left operand remains unchanged.
Example:
let a = 5;
let b = 10;
a &&= b;
console.log(a); // 10
The ||=
operator performs a logical OR operation and assigns the result back to the left operand if the left operand is falsy; otherwise, the left operand remains unchanged.
Example:
let c = 0;
let d = 20;
c ||= d;
console.log(c); // 20
The ??=
operator performs a nullish coalescing operation and assigns the right operand to the left operand if the left operand is null
or undefined
; otherwise, the left operand remains unchanged.
Example:
let e;
let f = 30;
e ??= f;
console.log(e); // 30
2. Numeric Separators
ECMAScript 2021 brings numeric separators to enhance the readability of numeric literals. Using the underscore (_
) as a separator, developers can now separate digits within large numbers to make them more readable.
Example:
// Without numeric separator
const oneMillion = 1000000;
// With numeric separator
const oneMillionReadable = 1_000_000;
console.log(oneMillion === oneMillionReadable); // true
3. Promise.any()
Promise.any() is a new addition to the ECMAScript 2021, which allows developers to handle multiple promises concurrently. It accepts an iterable of promises and returns a promise that is fulfilled by the first promise to be fulfilled among the input promises, or rejected if all input promises are rejected.
Example:
const promise1 = new Promise((resolve, reject) =>
setTimeout(reject, 100, 'Error 1'));
const promise2 = new Promise((resolve, reject) =>
setTimeout(resolve, 200, 'Success'));
const promise3 = new Promise((resolve, reject) =>
setTimeout(reject, 300, 'Error 2'));
Promise.any([promise1, promise2, promise3])
.then((value) => console.log(value)) // "Success"
.catch((errors) => console.error(errors));
As always, use new features at your own risk! As of early 2023 all of these features are pretty well integrated: