Categories
JavaScript

What’s New in ES2022?

Spread the love

The following new fearures be included in ES2022.

String.prototype.replaceAll()

This method replaces all occurrences of a substring within a string with another substring. Prior to this, you had to use regular expressions or iterate through occurrences manually.

To use it, we can write something like:

const str = 'foo bar foo baz';
const newStr = str.replaceAll('foo', 'qux');
console.log(newStr); // Output: 'qux bar qux baz'

Promise.any()

This method returns a single Promise that resolves as soon as any of the provided promises resolves, or rejects if all of the provided promises are rejected.

To use it, we can write something like:

Promise.any([promise1, promise2, promise3])
    .then((value) => {
        console.log(value); // Output: value of the first resolved promise
    })
    .catch((error) => {
        console.error(error); // Output: AggregateError containing errors of all rejected promises
    });

WeakRefs

Weak references allow you to hold references to objects without preventing them from being garbage collected. This can be useful in scenarios where you need to keep track of objects without preventing their natural cleanup.

Numeric Separators: Numeric separators allow you to make numeric literals more readable by inserting underscores (_) between groups of digits.

For example we write

const billion = 1_000_000_000;
const binary = 0b1010_0001_1001_0000;

Promise.allSettled()

This method returns a promise that resolves after all of the given promises have either resolved or rejected, with an array of objects that each describes the outcome of each promise.

To use it, we can write something like

Promise.allSettled([promise1, promise2, promise3])
    .then((results) => {
        console.log(results);
    });

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *