Tutorial

Learn About New JavaScript Features in ES2020

Updated on December 24, 2020
authorauthor

Joshua Hall and Natalia Vargas-Caba

Learn About New JavaScript Features in ES2020

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.

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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Joshua Hall

author



Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.