What's new in Javascript 21 - ES12

4 new feature that you are going to love

Featured on Hashnode
Featured on daily.dev
What's new in Javascript 21 - ES12

Just like every year, Javascript brings in new features. This year javascript is bringing 4 new features, which are almost in production rollout. I won't be wasting much more time and directly jump to code with easy to understand examples.

Use the latest node version, if you want to play around with these features. 15.8.0 worked fine for me.

Once the compatible node version is available, simply create a new JS file, and let's get started.

In case you prefer to watch video and use code examples below, here is a video for you.

Replace all - Global replace

const str = "Do yahoo people use yahoo search?";
const newStr = str.replaceAll("yahoo", "Yahoo!");
console.log(newStr);

with this new replaceAll, it replaces all instances of a word provided in the first argument. In case you want to use any regex expression, that can be done by /expression/g, passed in first argument.

Promise Any

Promise.any gives you a successful response if any one of the promise is resolved.

const rejectMe = new Promise((_, reject) => reject("Path issues"));
const resolveMe = new Promise(resolve => resolve())

Promise.any([rejectMe, resolveMe, rejectMe,])
.then(() => console.log("handle resolve"))
.catch(e => console.log("rejected"))

Here if in place of any, Promise.race is used, it will get a rejection response.

Numeric separators

Really a fancy name to make numbers more readable. This feature is now being supported by many languages.

const num = 100_000
console.log(num)

Logical Assignment Operators

Just like += or *=, we have now logical assignment operators available to us. You can use &&= or ||=. Here is an easy example.

function cartTotal(value){
    value ??= 0
    console.log("Your total is: ", value)
}

cartTotal()
cartTotal(20)

weakRef

This one is easy to understand by very tricky to get an hands on example. When an object no longer have strong reference to any variable or part of code, JS engine's garbage collector may destroy and reclaim it's memory. A very standard process of how GC works. When we store such weak refs in cache, it sometimes creates a little issue and hopefully in near future, this will be resolved. TC 39 WeakRef proposal You should really take some time and read this official guide that is writted in very depth and use cases.

Thanks for reading and we will bring more awesome articles to you. Subscribe to LCO. Have a great day!

Did you find this article valuable?

Support Learn Code Online by becoming a sponsor. Any amount is appreciated!