ES2021 new features
Maulik Thaker
Posted on March 1, 2021
ES2021 is the version of ECMAScript corresponding to the year 2021. Some features they've added into this version which is very much interesting.
The new JavaScript features in ES2021 are:
A. String.prototype.replaceAll()
A new replaceAll()
method has been added to the String prototype. See below example:
const str = "Apple is good for health. You should consume
Apple daily."
const strReplace = str.replaceAll("Apple", "Banana");
console.log(strReplace); // Banana is good for health. You should consume Banana daily.
B. Private methods & Private Accessors
We can restrict the method being called outside of the class by generating private methods.
Class Person{
#showTypeMethod(){
console.log("This is a type");
}
showHelloMethod(){
console.log("Hello World");
}
}
const person = new Person();
person.showHelloMethod(); // Hello World
person.showTypeMethod(); // Error: person.showTypeMethod is not a function
Here, you can make your showTypeMethod()
private by putting #
before function name. So now our #showTypeMethod()
is private to our class only. If you try to access this method outside of person class then it will cause an error.
C. Promise.any
Promise.any gives you a signal as soon as one of the promises fulfills. This is similar to Promise.race, except Promise.any doesn’t reject early when one of the promises rejects.
const myFetch = url => setTimeout(() => fetch(url), Math.floor(Math.random() * 3000));
const promises = [
myFetch('/endpoint-1'),
myFetch('/endpoint-2'),
myFetch('/endpoint-3'),
];
// Using .then .catch
Promise.any(promises) // Any of the promises was fulfilled.
.then(console.log) // e.g. '3'
.catch(console.error); //All of the promises were rejected.
// Using async-await
try {
const first = await Promise.any(promises); // Any of the promises was fulfilled.
console.log(first);
}catch (error) { // All of the promises were rejected
console.log(error);
}
D. Logical Assignment Operators
Assignment operators are used widely in JavaScript to compare and conditionally checked numbers, arguments etc. Normally we write the if condition as below:
let x = 1;
let y = 2;
if(x){
x = y;
}
console.log(x);
But using assignment operator we can shorthand the if condition like below:
let x = 1;
let y = 2;
x&&=y;
console.log(x);
E. WeakRef & Finalizer
Main use of weak references is to implement caches or mappings to large objects. In many scenarios, we don't want to keep a lot of memory for a long time saving this rarely used cache or mappings. We can allow the memory to be garbage collected soon and later if we need it again, we can generate a fresh cache. If variable is no longer reachable, JavaScript garbage collector automatically removes it.
const callback = () => {
const aBigObj = {
name: "Hello world"
};
console.log(aBigObj);
}
(async function(){
await new Promise((resolve) => {
setTimeout(() => {
callback();
resolve();
}, 2000);
});
})();
When executing above code, it prints "Hello world" after 2 seconds. Based on how we use the callback()
function, aBigObj
is stored in memory forever, may be.
Let us make aBigObj
a weak reference.
const callback = () => {
const aBigObj = new WeakRef({ name: "Hello world" }); console.log(aBigObj.deref().name);}
(async function(){
await new Promise((resolve) => {
setTimeout(() => {
callback(); // Guaranteed to print "Hello world"
resolve();
}, 2000);
});
await new Promise((resolve) => {
setTimeout(() => {
callback(); // No Gaurantee that "Hello world" is printed
resolve();
}, 5000);
});
})();
The first setTimeout()
will surely print the value of name. That is guaranteed in the first turn of event loop after creating the weak reference.
But there is no guarantee that the second setTimeout()
prints "Backbencher". It might have been sweeped by the gargage collector. Since the garbage collection works differently in different browsers, we cannot guarantee the output. That is also why, we use WeakRef
in situations like managing cache.
FinalizationRegistry
is a feature of WeakRef which lets programmers register callbacks to be invoked after an object is garbage collected.
const registry = new FinalizationRegistry((value) => {
console.log(value);
});
Here registry is an instance of FinalizationRegistry
. The callback function passed to FinalizationRegistry
gets triggered when an object is garbage collected.
(function () {
const obj = {};
registry.register(obj, "Hello World");
})();
When obj is garbage collected, the second argument of .register()
method is passed to the callback function. So, according to our code logic, when obj is garbage collected, "Hello World" is passed to the callback function and is printed in the console.
F. Numeric Seperators
let x = 1000000; // Not in human readable format right?
console.log(x);
Using Regular Number Literals:
let x = 1_000_000;
console.log(x); // 1000000
For more information, you can visit this link.
There may be many features that changed or added into ES12 but above is most common one where there are mostly useful and effective.
Posted on March 1, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.