2 min read
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 is a truthy, or return
a is falsy.
a &&= b returns
a is truthy, or
a is falsy.
a ??= b returns
undefined, or returns
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.
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 –
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.