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.
a &&= b
returns b
if a
is truthy, or a
if a
is falsy.
a ??= b
returns b
if a
is null
or undefined
, or returns a
if a
is truthy.
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:
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:
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:
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.
Top comments (2)
Great article! I enjoyed trying these features out in the Chrome console while reading.
Thanks, Derek!