Six New JavaScript Features You Need to Know About in ES2020

July 21, 2020

ECMAScript 2020 (ES2020) has been finalized and was formally approved last month. The few features being introduced this year are subtly powerful. Several features offer functionality that we’ve had in many back-end languages for years, and they’re sure to make your life easier. We’re going to cover six features that you’ll want to start using ASAP (if you aren’t already).

Here are top six ES2020 features making our programming lives easier:

  • Promise.allSettled()
  • Optional chaining
  • BigInt
  • Nullish coalescing operator
  • String.matchAll()
  • Dynamic imports

Promise.allSettled():

This feature takes an iterable object containing promises and returns its own promise once they’ve all completed. It includes an array of objects that describe the outcome of each promise (whether they were resolved or rejected), as well as the values. This is helpful for weeding out any rejected promises. Compatible with: BABEL ^7.0, EDGE, CHROME, FIREFOX, TYPESCRIPT ^3.7, NODE.JS ^12.9

getProjects = () => {
	const promise1 = getProjectById(94236)
	const promise2 = getProjectById(95084)
	const promise3 = getProjectById(10603)
	const promise4 = getProjectById(90000000000) // invalid ID

	const promises = [promise1, promise2, promise3, promise4]

	Promise.allSettled(promises).then(results => {
		let fulfilledResults = 
			results.filter(r => r.status === 'fulfilled');

		console.log(results)
	});
};

OUTPUT

[
	0: {status: "fulfilled", value: {…}}
	1: {status: "fulfilled", value: {…}}
	2: {status: "fulfilled", value: {…}}
	3: {status: "rejected", reason: Error: Not Found...
]

Dynamic Imports:

This is a function-like import that allows you to load a module from anywhere in your application code. This feature can be especially helpful for when you need to provide the application with data at runtime. For example, if you have config files somewhere that have some variable you need to access, you can import this anywhere at any point—unlike static imports. It also supports await. Compatible with: BABEL ^7.0, EDGE, CHROME, FIREFOX, TYPESCRIPT ^3.2, NODE.JS 13.2

import('../../config.json').then(module => {
  // do something with module
})
.catch(err => {
  console.log(err.message  );
});

Optional Chaining:

An operator ?. that allows you to read properties within nested objects (objects proper, arrays, functions) without checking the validity of objects in the chain. If we try to access a nullish property without using the Optional Chain operator, we’ll get an error. But with this new operator, we get undefined, which is a lot easier to work with. This operator can also be used in method chaining. This feature is very simple, very powerful, and we’ll use it a lot. Compatible with: BABEL ^7.0, EDGE, CHROME, FIREFOX, TYPESCRIPT ^3.7, NODE.JS 14

const bookObject = {
	title: "A title",
	description: "A description"
}

const lastName = bookObject.author?.firstName;

// will be undefined instead of throwing an error

Nullish Coalescing Operator:

A logical operator denoted by ??. The right-side operand is returned when the left side operand is null or undefined. Otherwise, the left side operand is returned. Yet another simple but powerful feature that you can expect to use frequently. Compatible with: BABEL ^7.0, EDGE, CHROME, FIREFOX, TYPESCRIPT ^3.7, NODE.JS 14

const foo = null ?? 'Some default';

console.log(foo); // output: "Some default"

let someUndefined;

const bar = someUndefined ?? 100;
// when left side is nullish, returns right side operand

console.log(bar); // output: 100

String.matchAll():

This is a new method attached to the String object that returns an iterator of all results from matching a string against a regexp. This feature has great potential for assisting in data massaging and data cleanup, especially if used with named groups. If you use named groups in your regex pattern, matchAll makes it really easy to grab those values from the returned results.

As you can see in the example below, we have named groups in our regular expression: “year”, “month”, “day”, and “time”. The output from the example shows the matches from comparing the dateString to the regexp. It also includes the captured groups from the match, presented to us in key value pairs. Compatible with: BABEL ^7.0, EDGE, CHROME, FIREFOX, TYPESCRIPT ^3.7, NODE.JS 12

let dateString = '1910-May-09 09:05, 2020-June-12 11:05';

let regexpDateFormat = 
	/(?<year>\d{4})-(?<month>\w+)-(?<day>\d{2}) (?<time>\d{2}:\d{2})/gu;

let array = Array.from(dateString.matchAll(regexpDateFormat));

console.log(array[0]);

OUTPUT

[
	0: "1910-May-09 09:05",
	1: "1910",
	2: "May",
	3: "09",
	4: "09:05",
	groups: {year: "1910", month: "May", day: "09", time: "09:05"},
	index: 0,
	input: "1910-May-09 09:05, 2020-June-12 11:05",
	length: 5
]

Big Int:

This is a new primitive that can represent arbitrary large numbers greater than 2^53, which is the max safe integer for a Number primitive that JavaScript can work with. You define Big Int by placing an “n” at the end of some integer or by using the constructor of BigInt to transform a number to a Big Int.

This is especially useful in areas that use really big numbers, such as cryptography, or even astronomy. In this example below, we’re converting parsecs to kilometers, and end up with numbers in the quadrillions. Compatible with: BABEL ^7.0*, EDGE, CHROME, FIREFOX, TYPESCRIPT ^3.2, NODE.JS

*Babel does not support Big Int exponentiation.

// The letter n is appended to distinguish it as a BigInt
const someBigInt = 340n;

// A Number can be converted to a BigInt
const someNumber = 467;
const someBigInt = BigInt(someNumber);
// The exoplanet kepler-150 is a distance of 914 parsecs
let distanceInParsecs = 914n;

// 1 parsec = aprox 31 trillion km (31000000000000)
let parsecToKm = 10n ** 12n * 31n; 

let distanceInKm = distanceInParsecs * parsecToKm;

console.log(distanceInKm);

// Output: 28334000000000000n

What else is included in ES2020

There’s more to come, too. Keep an eye out for other ES2020 features like import.meta and globalThis.

As a bonus, below are a few new web APIs I’m looking forward to using. These are currently in draft status, but they’re worth checking out when they’re released. Some of them you may be interested in from a privacy and security standpoint.

If, like me, you’re interested in contributing to the development of ECMAScript or other web technologies, there are several ways to contribute. Below are a few links to resources you can use to help shape the future of internet technology:


What ES2020 features are you most excited about? Are you also a fan of the six features I’ve highlighted above? Send me a message or comment below, I’d love to hear what you think.

Sign Up to Hear More

Get notified when more posts like “Six New JavaScript Features You Need to Know About in ES2020” are available.

  • This field is for validation purposes and should be left unchanged.

Alison Tinker

Software Developer
Alison is a full-stack developer with experience in web design, front-end, and back-end technologies. She has over 9 years of experience developing performant, responsive, and accessible web applications.

Leave a Reply

Your email address will not be published. Required fields are marked *