Skip to content
ES2020 Features

ES2020 JavaScript features

In the past few weeks, I’ve written several posts on ES2020 features, and in this post, I will summarize some of my favorite features that we can start using right away.

Nullish Coalescing Operator (??)

It is a logical operator through which we can set a fallback value when compared to values that are null/undefined. Usually, we use the logical OR (||) operator for null check but treats falsy values like 0 as false and returns the default value.

const data={};
const username = data.name ?? 'default name';
console.log(username); // default name

Read more: Nullish Coalescing Operator (??)

Optional Chaining (?.)

In JavaScript when accessing deeply nested objects if anything goes wrong it results in a runtime error. Using the optional chaining operator we can safely fallback to undefined instead of throwing an unexpected error.

const movie = {
   name: 'Nomadland',
   year: 2020,
}

const rating = movie.rating.imdb;
console.log(rating);
// Error: movie.rating is undefined

// using Optional chaining
const getRating = movie.rating?.imdb;
console.log(getRating);
// undefined

Combining this with the Nullish Coalescing operator is so cool.

const data = { };
const name = data.user?.name ?? 'not found';
console.log(name); // not found

Read more: Optional Chaining (?.) in JavaScript

Promise.allSettled()

The Promise.allSettled() is a promise that accepts an array of promises and is resolved only when all the promises are settled i.e either fulfilled or rejected. The output is an array of objects with all the results of individual promises.

const promise1 = 1;
const promise2 = Promise.resolve(22);
const promise3 = new Promise((resolve, reject) => {
    setTimeout(resolve, 2, 'three');
});

Promise.allSettled([promise1, promise2, promise3])
    .then(values => console.log(values))
    .catch(error => console.log(error));

// Output
Array[Object {
    status: "fulfilled",
    value: 1
}, Object {
    status: "fulfilled",
    value: 22
}, Object {
    status: "fulfilled",
    value: "three"
}]

Read more: Promise.all() vs Promise.allSettled() in JavaScript

Dynamic imports

As suggested by the name we can import files dynamically as needed based on a function call or an if condition.

Read more about this ES2020 feature

globalThis

The global object or this keeps changing based on the runtime and context although it is the same JavaScript everywhere it is

  • window/self in the browser
  • self in web workers and
  • global in Node.js

In case we get to write some cross-platform code this will result in inconsistent code and potential errors. We can solve this problem by using globalThis.

globalThis.setTimeout(() => console.log("foo"),1000)
// Output: foo

Read more: globalThis – MDN

Conclusion

I really like the first two features and I believe using them will make my code clean and efficient. So what is your favorite feature?