DEV Community

Cover image for Top 3 New JavaScript ES 2021 (ES 12) Features I Am Excited About
Nick Bull
Nick Bull

Posted on • Originally published at blog.nickbulljs.com

 

Top 3 New JavaScript ES 2021 (ES 12) Features I Am Excited About

I’m using the new ECMAScript 2021 features for over a year, thanks to Babel. Almost all the features are useful, but I most liked only three of them. They saved me a lot of time and made my code more readable.

Here they are:

1. Logical Assignment Operator

Logical assignment operator combines the logical operations (like ?? or && or ||) with an assignment (=)

Here are the examples:

a ||= b returns a if a is a truthy, or return b if a is falsy.

1.png

a &&= b returns b if a is truthy, or a if a is falsy.

2.png

a ??= b returns b if a is null or undefined, or returns a if a is truthy.

3.png

At first, it was slightly tricky to instantly understand what these operators do during a code review, but after a few weeks, everyone in the team got good with it.

2. Promise.any

Promise.any accepts an array of promises and resolves as soon as any of the supplied promises become resolved.

Sounds difficult, so here is an example:

4.png

We make three requests simultaneously. When one of the requests resolves, Promise.any also resolves and log the first resolved request in the console (in our example, it’s Google)

If all promises were rejected, Promise.any throws a new type of error – AggregateError.

What’s new about it is the AggregateError object represents an error where several errors are wrapped in a single error.

Here is how it looks:

5.png

e.errors is an array of the errors object.

3. Numeric Separators

Numeric Separators give us the ability to separate thousands with an underscore (_) in numeric literals.

How it’s useful?

It makes our code more informative and readable.

Here is an example:

6.png


If you want to try these three new features of ES2021 now, you can use these Babel plugins:


In the end...

If you like this article, share it with your colleagues or friends and check me on Twitter.

And also, every week I send out a "3–2–1" newsletter with 3 tech news, 2 articles, and 1 advice for you.

📌 Join my 3–2–1 newsletter here 📌

Top comments (2)

Collapse
 
derekkrause profile image
Derek Krause

Great article! I enjoyed trying these features out in the Chrome console while reading.

Collapse
 
nickbulljs profile image
Nick Bull

Thanks, Derek!