Es2021 Features part1

I started writing this series of posts about new javascript features during the 2020 quarantine. Now it’s 2021 and there are still severe restrictions in Italy. This list is undoubtedly the most strict for you. So let’s start with the features of ES2021:

String replaceAll()

This method just replace all the occurrences of a word in a string with another word (the old replace() replaces only the first one). Easy and fast, let’s try:

let string = "In this program there are only bugs, only and only bugs, and more bugs! you can only produce bugs."

string.replaceAll("bugs", "love");
// 'In this program there are only love, only and only love, and more love! you can only produce love.'

Promise.any()

This is a promise that takes as an input an array of promises and resolves with the first one is resolved. It seems difficult, it’s not.

const slow = new Promise((resolve) => setTimeout(resolve, 500, 'Too slow'));
const fast = new Promise((resolve) => setTimeout(resolve, 100, 'Fast!'));

Promise.any([slow, fast]).then((value) => console.log(value));
// Fast!

If I had used Promise.all instead, I would have got an array with each of the results

Promise.all([slow, fast]).then((value) => console.log(value));
// ['Too slow', 'Fast!']

If none is resolved an error is raised

Uncaught (in promise) AggregateError: All promises were rejected

To be completely honest I don’t see a single scenario where this feature can come in handy.

Logical Assignment Operator

Combines a logical operator with an assignment.

Assign a value to a variable if this is falsy (&&=):

let first = 'first value'
let last = 'last value'

first &&= last // last value

// It can be written also like that
if(first) first = last

Assign a value to a variable if this is falsy (||=):

let first = 'first value'
let last = 'last value'

first ||= last // 'first value'

// It can be written also like that
if(!first) first = last

Assign with Nullish Coalescing operator (??=):

let first = null
let last = 'last value'
first ??= last // 'last value'

More information about the nullish coalescing operator in this post

#Underscores as Numeric Seperator

Just for better readability, we can use the underscore as a separator between numbers

const number = 1000_000_000;
console.log(billion); // 1000000000

No old pieces for you today, I leave you the trailer of the movie that I can’t wait to see this year.

Cry Macho, Clint Eastwood, 90 and still wonderful.

Irene Iaccio

Freelance web developer

Subscribe to the monthly digest!

I'll use your email only to send you the latest posts once a month.