DEV Community

loading...
Cover image for Modern Javascript - II

Modern Javascript - II

sinhapiyush profile image Piyush Sinha Originally published at devdojo.com ・3 min read

JavaScript has been evolving very rapidly in recent years. Especially after the release of ES6 in 2015, things have been great. In this article, we'll discuss the features introduced in the ES2020 version.

Optional Chaining

The optional chaining operator (?.) provides a way to simplify accessing values through connected objects when it's possible that a reference or function may be undefined or null.

For example, consider an object blog which has a nested structure. Without optional chaining, looking up a nested sub-property requires validating the references in between, such as:

const blog = {
  title: "My Blog",
  author: {
    name: "John Doe",
    links: {
      website: "https://john.tech/",
    },
  },
};

const linkToWebsite =
  blog &&
  blog.author &&
  blog.author.links &&
  blog.author.links.website;
Enter fullscreen mode Exit fullscreen mode

By using the ?. operator, JavaScript knows to implicitly check to be sure references in between is not null or undefined before attempting to access further. If the reference is null or undefined, the expression automatically short-circuits, returning undefined. Below is the same example using optional chaining:

//ES2020
const linkToWebsite = blog?.author?.links?.website;
Enter fullscreen mode Exit fullscreen mode

Nullish Coalescing Operator

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined and otherwise returns its left-hand side operand.

The result of a ?? b is:

  • if a is defined, then a,
  • if a isn’t defined, then b.
const res = (a !== null && a !== undefined) ? a : b;

//ES2020
const res = a??b;
Enter fullscreen mode Exit fullscreen mode

Dynamic Imports

The standard import syntax is static and will always result in all code in the imported module being evaluated at load time. In situations where you wish to load a module conditionally or on-demand, you can use a dynamic import instead.

  • To dynamically import a module, the import keyword may be called as a function. When used this way, it returns a promise.
//ES2020
import('/modules/my-module.js')
  .then((module) => {
    // Do something with the module.
  });
Enter fullscreen mode Exit fullscreen mode
  • This form also supports the await keyword.
//ES2020
let module = await import('/modules/my-module.js'); 
Enter fullscreen mode Exit fullscreen mode

BigInt

It is a special numeric type that provides support for integers larger than 253- 1, which is the largest number Javascript can reliably represent with the Number primitive and represented by the Number.MAX_SAFE_INTEGER constant.

let previousMaxSafe = Number.MAX_SAFE_INTEGER;
// 9007199254740991
previousMaxSafe = previousMaxSafe + 1;
// 9007199254740992
previousMaxSafe = previousMaxSafe + 1;
// 9007199254740992, value stays the same
Enter fullscreen mode Exit fullscreen mode

A BigInt is created by appending n to the end of an integer literal or by calling the function BigInt().

//ES2020
let previousMaxSafe = BigInt(Number.MAX_SAFE_INTEGER);
// 9007199254740991n
previousMaxSafe = previousMaxSafe + 1n;
// 9007199254740992n
previousMaxSafe = previousMaxSafe + 1n;
// 9007199254740993n, this works now!
Enter fullscreen mode Exit fullscreen mode

Promise.allSettled()

The Promise.allSettled() method returns a promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise. It is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you'd always like to know the result of each promise.

//ES2020
const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'Something went wrong'));
const promises = [promise1, promise2];

Promise.allSettled(promises).
  then((results) => results.forEach((result) => console.log(result.status)));

// expected output:
// "fulfilled"
// "rejected"

Enter fullscreen mode Exit fullscreen mode

Conclusion

ES2020’s new features add even more flexibility and power to the constantly evolving Modern JavaScript. I hope I was able to introduce you to some of the features.

Discussion (6)

pic
Editor guide
Collapse
ogrotten profile image
ogrotten • Edited

In Promise examples, using setTimeout can be confusing.

The explanation has already said that it's for async operation. Unrelated code, in the middle of the example, only for simulation of an already explained effect, can add to or otherwise create confusion. To a newbie, it seems like it is a required part of the Promise syntax.

No other example in these 2 blog posts do this same kind of interruption of example.

This is my biggest beef with Promise tutorials across the entire internet. By the time explanation of Promises is reached, the event loop, synchronous execution, and the need for asynchronous execution has all been explained. At that point, putting setTimeout in the middle of the code is redundant.

To simulate some slow operation (an api, or db call, or what have you), build the example Promise to refer to an external function (with a setup section similar to the object in the first example on this post), and then have that code with the setTimeout. That way, the direct example remains clean.

Another solution is for the example to refer to any of the freely available api across the web... Pokemon, Star Trek, etc.

Collapse
sinhapiyush profile image
Piyush Sinha Author

Agreed. It may create confusion for beginners. Instead of faking an API call... fetching data from any free API service makes more sense. I will keep that in mind for future articles.

Collapse
eduardopech profile image
Eduardo Pech

Thanks for sharing. I don't knew about nullish coalescing operator (??). It's very interesting to use.

Collapse
sinhapiyush profile image
Piyush Sinha Author

?? operator makes the conditional checks an easy task. Really useful.

Collapse
sumeetbajra profile image
Sumit Bajracharya

What's the difference between a??b and a || b?

Collapse
sinhapiyush profile image
Piyush Sinha Author

a ll b returns b if a is falsey value.

In Javascript, a lot of values are falsey, like empty strings, the number 0, undefined, null, false, NaN, and so on.

However, a lot of times you might want to check if a variable is either undefined or null, like when it's okay for a variable to have an empty string, or even a false value. In such cases, (??) is used.