New features in ES2021 JavaScript

Home » Programming » New features in ES2021 JavaScript
JS ES2021

New features in ES2021 JavaScript

  • Features of ES2021
    • replaceAll()
    • Promise.any
    • &&=||= and ??=
    • Numeric separators

 

String replaceAll() Method

JavaScript string has a replace() method. It can be used to replace a string with another string.

The replace() method only replaces the first occurrence. That is the reason the second occurrence of dog is not replaced. We can use a regular expression to do full replacement using the same replace() method

String.prototype.replaceAll() is now available and it replaces all occurrences of string without using a regular expression.

 

Promise.any()

Promise.any() resolves if any of the supplied promises is resolved. Below we have 3 promises, which resolves at random times.

From py1, py2, py3 whichever is resolved first, that is taken by promise.any()

What if none of the promises resolve? In that case Promise.any throws an AggregateError exception. We need to catch it and handle it.

Check the below example for more details.

Promise.any()

 

 

Logical Assignment Operator

Logical assignment operator combines the below logical operations:

  • &&
  • ||
  • ??

The above logical assignments can be combined with assignment operator.

Line no 3 can be explained as below:

In other way it can be written as:

Explanation: Since a is a truthy value, it is assigned with the value of b, i.e. 2.

The way we did it of && operator, we can implement the same for || and ?? operators.

 

Logical assignment operator with ||

Line no 3 can be explained as below:

Explanation: The assignment operation happens only if a is a falsy value. In the code, a contains 1 which is a truthy value and hence, assignment does not happen. That is why our code prints 1 in the console.

 

Logical assignment operator with ??

?? is Nullish Coalescing operator in JavaScript. It specifically checks if a value is null or undefined.

Line no 2 can be explained as – if the value of a is null or undefined the right hand side of ?? is evaluated and assigned to b.

Another example with = operator:

Line 3 can be described as follows:

Here the value of a is undefined. As a result, the phrase on the right side is evaluated and set to 2.

 

Underscores as Numeric Separator

ES2021 supports _ (underscore) which can be placed as numeric separator. Normally we write one billion as 1000000000, but with ES2021 _ support it can be written as 1000_000_000 in the code and it is easy to read.

It is also supports floating pointer numbers.

It’s important to note that all numbers in JavaScript are floating-point numbers.

To see which ES2021 features are supported by Nodejs, visit https://node.green/.