Tutorial

Learn About New JavaScript Features in ES2020

JavaScript

Introduction

In this article, you’ll learn about new JavaScript features launched in the most recent upgrade, ES2020. Features such as the Nullish Coalescing and Optional Chain Operators help define your JavaScript syntax, while Dynamic Import keeps your code modular.

Private Class Variables

Classes contain properties you may employ into reusable modules. If you reuse those properties in various files, you may not want everything made available globally.

To resolve this, a private class variable reserves properties and methods for use within a class. A hash symbol in front of the property and method denotes the private class variable.

class Message {
  #message = "Howdy";

  greet() { 
    console.log(this.#message); 
  };
}; 

const greeting = new Message()

greeting.greet() // Howdy
console.log(greeting.#message) // #message is not defined

Notice that calling on the greet method outside the class returns a value. A console.log on the property made private returns an error.

Promise.allSettled()

When you work with multiple promises, especially when they rely on each other, it could be useful to log each process to debug errors.

With Promise.allSettled(), you can create a new promise that returns when promises passed in as arguments have resolved:

const p1 = new Promise((res, rej) => setTimeout(res, 1000));

const p2 = new Promise((res, rej) => setTimeout(rej, 1000));

Promise.allSettled([p1, p2]).then(data => console.log(data));

This will output an array of objects with a status and value on each promise:

Output
[ Object { status: "fulfilled", value: undefined}, Object { status: "rejected", reason: undefined} ]

Here, Promise.allSettled() provides an array with the status and value of the p1 and p2 promises.

Nullish Coalescing Operator

As JavaScript is loosely typed, keep in mind of truthy and falsy values when assigning variables. If you have an object with data, you may want to allow for falsy values such as an empty string or the number 0.

The Nullish Coalescing Operator (??) identifies and returns falsy values when the left operand is not null or undefined.

let person = {
  profile: {
    name: "",
    age: 0
  }
};

console.log(person.profile.name || "Anonymous"); // Anonymous
console.log(person.profile.age || 18); // 18

In contrast, note that the OR Operator (||) returns the right operand if the left is falsy.

console.log(person.profile.name ?? "Anonymous"); // ""
console.log(person.profile.age ?? 18); // 0

Instead, the Nullish Coalescing Operator returns falsy values as neither the name and age properties are null or undefined.

Optional Chaining Operator

Another way to interact with falsy values is with Optional Chaining Operator (?.). If a reference is nullish, the operator will provide a way to access undefined properties within objects.

let person = {};

console.log(person.profile.name ?? "Anonymous"); // person.profile is not defined
console.log(person?.profile?.name ?? "Anonymous"); // no error 
console.log(person?.profile?.age ?? 18); // no error

Instead of throwing an error, the Optional Chaining Operator allows you to interact with properties that evaluate to undefined.

Note: Refer to this post to learn more about Optional Chaining and Nullish Coalescing.

BigInt

The largest number JavaScript can handle is 2^53, which you can verify with the property MAX_SAFE_INTEGER.

const max = Number.MAX_SAFE_INTEGER;

console.log(max); // 9007199254740991

Any number above the value in the max variable may not remain reliable:

console.log(max + 1); // 9007199254740992
console.log(max + 2); // 9007199254740992
console.log(max + 3); // 9007199254740994
console.log(Math.pow(2, 53) == Math.pow(2, 53) + 1); // true

With the built-in BigInt object, append n to the end of each large integer for your calculations. BigInt numbers can compute only with other BigInt digits.

const bigNum = 100000000000000000000000000000n;

console.log(bigNum * 2n); // 200000000000000000000000000000n

The BigInt value for bigNum is multiplied with 2n to produce 200000000000000000000000000000n.

Dynamic Import

If you had a file of utility functions, you may not use all of them, and importing their dependencies could be a waste of resources. Now async/await comes with additional functionality to import your dependencies wherever necessary.

Here is an example of an utility function in a math.js file:

math.js
const add = (num1, num2) => num1 + num2;

export { add };

Here is an example of a index.js file using the utility function:

index.js
const doMath = async (num1, num2) => {
  if (num1 && num2) {
    const math = await import('./math.js');
    console.log(math.add(5, 10));
  };
};

doMath(4, 2);

In index.js, the await expression can now handle an import of math.js and use the logic contained within the file.

Conclusion

With each JavaScript upgrade, new features add dynamic functionality, defined properties, and greater performance from the feedback of its developers and community.

Creative Commons License