JavaScript ES 2021 Features You Need To Know

JavaScript ES 2021 Features You Need To Know

ยท

4 min read

Hello! ๐Ÿ‘‹ friends, ECMA Script has released some cool new features in JavaScript ES2021 version. Here in this article i have discussed some ES2021 features you should need to know.

Numeric Separators

Numeric separator is one of the useful feature that have been introduced in ES 2021. They make it easier to read large numbers in JavaScript by providing separation between digits using underscores _.

let myNumber = 1_000_000;
console.log(myNumber);  // output: 1000000

let num = 0.000_0002;
console.log(num);  // output: 2e-7

Replace All

The method replaceAll() is one of the feature i really like about ES2021. This method allows you to replace all the characters that you specify in a string without using a regex. The method replaceAll() takes two parameters: the character we want to replace and the character we want to replace it by.

let myStr = 'Prograssing';
console.log(myStr.replaceAll("s", "m"));
// output: Programming

Weak Reference

Another cool feature of ES2021 is WeakRef(). It's used to hold a weak reference to another object, which means it doesn't prevent the garbage collector from collecting the object, It's useful when we don't want to keep the object in memory forever.

const myObject = new WeakRef({
name: 'Jhon',
age: 25
});
// Read the object.
console.log(myObject.deref());
// output: {name: 'Jhon', age: 25}

// Access name.
console.log(myObject.deref().name);
// output: Jhon

Promise Any

Promise.any() takes an array of promises as an argument. If all the promises are resolved, the first resolved one will be returned by Promise.any(). If all the promises are rejected, you will get an error.

const promise1 = new Promise((resolve, reject) => {
     resolve('promise1 was resolved.');
});
const promise2 = new Promise((resolve, reject) => {
     resolve('promise2 was resolved.');
});
const promise3 = new Promise((resolve, reject) => {
     resolve('promise3 was resolved.');
});

let result = Promise.any([promise1, promise2, promise3]);
console.log(result); // output: promise1 was resolved.

Logical Assignment Operators

ES2021 has introduced three useful logical assignment operators: &&=, ||= and ??=. The logical assignment operator &&= is used two values. If the first value is truthy, the second value will be assigned to it.

let firstNum = 5;
let secondNum = 20;
firstNum &&= secondNum;
// output: 20

console.log(firstNum);
// output: 20

// Here is an equivalent to it:
if (firstNum) {
   firstNum = secondNum;
}

This are the some new features introduced in ES2021. If you like it, tell me in comment section below, or catch me on Twitter.