JavaScript ES12 Features – ECMAScript 2021

ECMAScript 2021 (ES12) 12th version of ECMAScript is now available, featuring new features and syntactic enhancements known as ECMAScript 2021 (ES12). On June 22, 2021, ECMA International published the final specifications. These enhancements have been made to make JavaScript more robust and to make it easier for developers to complete their tasks.

I’ll go through the top five features of ECMAScript 2021 in-depth so you can start using them in your projects and improve your JavaScript experience. This article can help both new and experienced developers.

Top 5 JavaScript Features Offered By ECMAScript 2021 Update

  1. Numeric Separators
  2. String.prototype.replaceAll
  3. Promise.any() and AggregateError
  4. Logical Assignment Operators
  5. Private Class Methods and Accessors

Numeric Separators

The numeric separators allow you to insert underscores between digits in literal numbers, making them easier to understand. When the files are process, the underscores will be strip away automatically. To learn how to utilize numeric separators, look at the following code excerpt.

// Decimal integer literal with digits grouped by thousand.
let n1 = 1_000_000_000;
console.log(n1); // This will print: 1000000000

// Decimal literal with digits grouped by thousand.
let n2 = 1_000_000_000.150_200
console.log(n2); // This will print: 1000000000.1502

// Hexadecimal integer literal with digits grouped by byte.
let n3 = 0x95_65_98_FA_A9
console.log(n3); // This will print: 641654651561

// BigInt literal with digits grouped by thousand.
let n4 = 155_326_458_156_248_168_514n
console.log(n4); // This will print: 155326458156248168514n

String.prototype.replaceAll

The String prototype’s replaceAll() method allows you to replace all instances of a sub-string without using regex. When the replace() is applies to a string, just the first instance of that value is replace. ReplaceAll(), on the other hand, allows you to replace all instances of a given value. To learn how to use replaceAll(), look at the following code sample.

// Declare a variable and store some value.
const orgStr = 'JavaScript, often abbreviated as JS, is a programming language that conforms to the ECMAScript specification. JavaScript is high-level, often just-in-time compiled and multi-paradigm.';

// To replace single instance, use replace().
let newStr = orgStr.replace('JavaScript', 'TypeScript');
console.log(newStr);

// To replace all instances, use replaceAll().
let newStr2 = orgStr.replaceAll('JavaScript', 'TypeScript');
console.log(newStr2);

Promise.any() and AggregateError

The Promise.any is the exact opposite of Promise.all(). If any of the promises are resolve, Promise.any() will be call. Promise.all(), on the other hand, will wait until all promises have been resolve. Following are the differences in any(), all(), and allSettled().

  • any(): If at least one promise is fulfilled, this will be executed; else, it will be refused.
  • all(): If all promises are resolved, this will execute, and if at least one promise is refused, it will reject.
  • allSettled(): If all promises have been resolved or refused, this will be executed.

To learn how to utilize Promise.any(), look at the following code sample.

// Create a Promise.
const promise1 = new Promise((resolve, reject) => {
    // After 2 seconds resolve the first promise.
    setTimeout(() => resolve("The first promise has been resolved."), 2000);
});

// Create a Promise.
const promise2 = new Promise((resolve, reject) => {
    // After 1 second resolve the second promise.
    setTimeout(() => resolve("The second promise has been resolved."), 1000);
});

// Create a Promise.
const promise3 = new Promise((resolve, reject) => {
    // After 3 seconds resolve the third promise.
    setTimeout(() => resolve("The third promise has been resolved."), 3000);
});

(async function () {
    const data = await Promise.any([promise1, promise2, promise3]);
    // Print the data returned from the first resolved Promise.
    console.log(data);
    // The above will print: The second promise has been resolved.
})();

An AggregateError Exception will be thrown if all of the Promises are denied. To learn how to handle the exception, look at the following code sample.

// Create a Promise.
const promise1 = new Promise((resolve, reject) => {
    // After 1 seconds rejects the first promise.
    setTimeout(() => resolve("The first promise has been rejected."), 1000);
});

// Create a Promise.
const promise2 = new Promise((resolve, reject) => {
    // After 500 milliseconds rejects the second promise.
    setTimeout(() => resolve("The second promise has been rejected."), 500);
});

// Try executing the Promises.
(async function () {
    try {
        const data = await Promise.any([promise1, promise2]);
        console.log(data);
    } catch (error) {
        // If all Promises gets rejected, then this try-catch block will handle
        // the aggregate errors.
        console.log("Error: ", error);
    }
})();

Logical Assignment Operators

In the ECMAScript 2021 release, three new logical assignment operators were include. These give a set of logical operators and assignment expressions in one package.

  1. Logical OR assignment operator ||=
  2. Logical AND assignment operator &&=
  3. Nullish coalescing assignment operator ??=

Logical OR assignment operator

If the left operand is false, the logical OR assignment operator ||= assigns the right operand to the left operand. Learn how to utilize the logical OR assignment operator in the following code sample.

// In the example, the ||= will check if the songsCount is false (0).
// If false, then the right value will be assigned to the left variable.
let myPlaylist = {songsCount: 0, songs:[]};
myPlaylist.songsCount ||= 100;
console.log(myPlaylist); // This will print: {songsCount: 100, songs: Array(0)}

Short-circuiting occurs when the logical OR assignment operator is use. This operator ||= is identical to the logical OR operator in the following expression.

a || (a = b)

Logical AND assignment operator

If the left operand is true, the logical AND assignment operator &&= only assigns the right operand to the left operand. Learn how to utilize the logical AND assignment operator in the following code sample.

// In the example, the &&= will check if the filesCount is true.
// If true, then the right value will be assigned to the left variable.
let myFiles = {filesCount: 100, files:[]};
myFiles.filesCount &&= 5;
console.log(myFiles); // This will print: {filesCount: 5, files: Array(0)}

Also short-circuiting is the logical AND assignment operator. The &&= operator is identical to the logical AND operator in the following expression.

a && (a = b)

Nullish coalescing assignment operator

If the left operand is null or undefined, the nullish coalescing assignment operator ??= only assigns the right operand to the left operand. The nullish coalescing assignment operator is demonstrate in the following code snippet.

// In the example, the ??= will check if the lastname is null or undefined.
// If null or undefined, then the right value will be assigned to the left variable.
let userDetails = {firstname: 'Ranjeet', age: 22}
userDetails.lastname ??= 'Andani';
console.log(userDetails); // This will print: {firstname: 'Ranjeet', age: 22, lastname: 'Andani'}

Also short-circuiting is the nullish coalescing assignment operator. This operator ??= is equal to the nullish coalescing operator in the following sentence.

a ?? (a = b)

Private Class Methods and Accessors – ECMAScript 2021 (ES12)

By default, the class methods and properties are public, however, private methods and properties may be establish by prefixing them with a hash #. Since the ECMAScript 2021 upgrade, privacy encapsulation has been require. Only members of the class have access to these secret methods and attributes. To discover how to utilize the private methods, look at the code excerpt below.

// Let's create a class named User.
class User {
    constructor() {}

    // The private methods can be created by prepending '#' before
    // the method name.
    #generateAPIKey() {
        return "d8cf946093107898cb64963ab34be6b7e22662179a8ea48ca5603f8216748767";
    }

    getAPIKey() {
        // The private methods can be accessed by using '#' before
        // the method name.
        return this.#generateAPIKey();
    }
}

const user = new User();
const userAPIKey = user.getAPIKey();
console.log(userAPIKey); // This will print: d8cf946093107898cb64963ab34be6b7e22662179a8ea48ca5603f8216748767

Private Getters and Setters are the private accessors. A Getter is used to get the value of a class property, whereas a Setter is used to set a class property’s value. A hash # prefix can be use to specify a private getter.

get #newAccountPassword() {}

Similarly, a hash # prefix may be use to specify a private setter.

set #generateAccountPassword(newPassword) {}

To learn how to utilize the private Getters and Setters, look at the code excerpt below.

// Let's create a class named Str.
class Str {
    // The private attributes can be created by prepending '#'
    // before the attribute name.
    #uniqueStr;

    constructor() {}

    // A private Setters can be created by prepending '#' before
    // the Setter name.
    set #generateUniqueStringByCustomLength(length = 24) {
        const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        let randomStr = "";

        for (let i = 0; i < length; i++) {
            const randomNum = Math.floor(Math.random() * characters.length);
            randomStr += characters[randomNum];
        }

        this.#uniqueStr = randomStr;
    }

    // Public Setter
    set setRandomString(length) {
        this.#generateUniqueStringByCustomLength = length;
    }

    // A private getter can be created by prepending '#' before
    // the Getter name.
    get #fetchUniqueString() {
        return this.#uniqueStr;
    }

    // Public Getter
    get getRandomString() {
        return this.#fetchUniqueString;
    }
}

const str = new Str();
// Calling a public Setter which will then access the private Setter
// within the class.
str.setRandomString = 20;

// Calling a public Getter which will then access the private Getter
// withing the class.
const uniqueStr = str.getRandomString;
console.log(uniqueStr); // This will print a random string everytime you execute the Getter after the Setter.

That’s all for this article We’ve finished studying all of the new features in JavaScript ES12 (ECMAScript 2021). You may now begin using the features listed above in your existing or future projects. if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn.

If you want to learn more about the JavaScript programming language then click the link to see our last article React vs Vue

Leave a Comment