What’s New in ES2018

Craig Buckler
Craig Buckler
Share

In this article, I’ll cover the new features of JavaScript introduced via ES2018 (ES9), with examples of what they’re for and how to use them.

JavaScript (ECMAScript) is an ever-evolving standard implemented by many vendors across multiple platforms. ES6 (ECMAScript 2015) was a large release which took six years to finalize. A new annual release process has been formulated to streamline the process and add features quicker. ES9 (ES2018) is the latest iteration at the time of writing.

Technical Committee 39 (TC39) consists of parties including browser vendors who meet to push JavaScript proposals along a strict progression path:

Stage 0: strawman – The initial submission of ideas.

Stage 1: proposal – A formal proposal document championed by at least once member of TC39 which includes API examples.

Stage 2: draft – An initial version of the feature specification with two experimental implementations.

Stage 3: candidate – The proposal specification is reviewed and feedback is gathered from vendors.

Stage 4: finished – The proposal is ready for inclusion in ECMAScript but may take longer to ship in browsers and Node.js.

ES2016

ES2016 proved the standardization process by adding just two small features:

  1. The array includes() method, which returns true or false when a value is contained in an array, and
  2. The a ** b exponentiation operator, which is identical to Math.pow(a, b).

ES2017

ES2017 provided a larger range of new features:

  • Async functions for a clearer Promise syntax
  • Object.values() to extract an array of values from an object containing name–value pairs
  • Object.entries(), which returns an array of sub-arrays containing the names and values in an object
  • Object.getOwnPropertyDescriptors() to return an object defining property descriptors for own properties of another object (.value, .writable, .get, .set, .configurable, .enumerable)
  • padStart() and padEnd(), both elements of string padding
  • trailing commas on object definitions, array declarations and function parameter lists
  • SharedArrayBuffer and Atomics for reading from and writing to shared memory locations (disabled in response to the Spectre vulnerability).

Refer to What’s New in ES2017 for more information.

ES2018

ECMAScript 2018 (or ES9 if you prefer the old notation) is now available. The following features have reached stage 4, although working implementations will be patchy across browsers and runtimes at the time of writing.

Asynchronous Iteration

At some point in your async/await journey, you’ll attempt to call an asynchronous function inside a synchronous loop. For example:

async function process(array) {
  for (let i of array) {
    await doSomething(i);
  }
}

It won’t work. Neither will this:

async function process(array) {
  array.forEach(async i => {
    await doSomething(i);
  });
}

The loops themselves remain synchronous and will always complete before their inner asynchronous operations.

ES2018 introduces asynchronous iterators, which are just like regular iterators except the next() method returns a Promise. Therefore, the await keyword can be used with for … of loops to run asynchronous operations in series. For example:

async function process(array) {
  for await (let i of array) {
    doSomething(i);
  }
}

Promise.finally()

A Promise chain can either succeed and reach the final .then() or fail and trigger a .catch() block. In some cases, you want to run the same code regardless of the outcome — for example, to clean up, remove a dialog, close a database connection etc.

The .finally() prototype allows you to specify final logic in one place rather than duplicating it within the last .then() and .catch():

function doSomething() {
  doSomething1()
  .then(doSomething2)
  .then(doSomething3)
  .catch(err => {
    console.log(err);
  })
  .finally(() => {
    // finish here!
  });
}

Rest/Spread Properties

ES2015 introduced the rest parameters and spread operators. The three-dot (...) notation applied to array operations only. Rest parameters convert the last arguments passed to a function into an array:

restParam(1, 2, 3, 4, 5);

function restParam(p1, p2, ...p3) {
  // p1 = 1
  // p2 = 2
  // p3 = [3, 4, 5]
}

The spread operator works in the opposite way, and turns an array into separate arguments which can be passed to a function. For example, Math.max() returns the highest value, given any number of arguments:

const values = [99, 100, -1, 48, 16];
console.log( Math.max(...values) ); // 100

ES2018 enables similar rest/spread functionality for object destructuring as well as arrays. A basic example:

const myObject = {
  a: 1,
  b: 2,
  c: 3
};

const { a, ...x } = myObject;
// a = 1
// x = { b: 2, c: 3 }

Or you can use it to pass values to a function:

restParam({
  a: 1,
  b: 2,
  c: 3
});

function restParam({ a, ...x }) {
  // a = 1
  // x = { b: 2, c: 3 }
}

Like arrays, you can only use a single rest parameter at the end of the declaration. In addition, it only works on the top level of each object and not sub-objects.

The spread operator can be used within other objects. For example:

const obj1 = { a: 1, b: 2, c: 3 };
const obj2 = { ...obj1, z: 26 };
// obj2 is { a: 1, b: 2, c: 3, z: 26 }

You could use the spread operator to clone objects (obj2 = { ...obj1 };), but be aware you only get shallow copies. If a property holds another object, the clone will refer to the same object.

Regular Expression Named Capture Groups

JavaScript regular expressions can return a match object — an array-like value containing matched strings. For example, to parse a date in YYYY-MM-DD format:

const
  reDate = /([0-9]{4})-([0-9]{2})-([0-9]{2})/,
  match  = reDate.exec('2018-04-30'),
  year   = match[1], // 2018
  month  = match[2], // 04
  day    = match[3]; // 30

It’s difficult to read, and changing the regular expression is also likely to change the match object indexes.

ES2018 permits groups to be named using the notation ?<name> immediately after the opening capture bracket (. For example:

const
  reDate = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/,
  match  = reDate.exec('2018-04-30'),
  year   = match.groups.year,  // 2018
  month  = match.groups.month, // 04
  day    = match.groups.day;   // 30

Any named group that fails to match has its property set to undefined.

Named captures can also be used in replace() methods. For example, convert a date to US MM-DD-YYYY format:

const
  reDate = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/,
  d      = '2018-04-30',
  usDate = d.replace(reDate, '$<month>-$<day>-$<year>');

Regular Expression lookbehind Assertions

JavaScript currently supports lookahead assertions inside a regular expression. This means a match must occur but nothing is captured, and the assertion isn’t included in the overall matched string. For example, to capture the currency symbol from any price:

const
  reLookahead = /\D(?=\d+)/,
  match       = reLookahead.exec('$123.89');

console.log( match[0] ); // $

ES2018 introduces lookbehind assertions that work in the same way, but for preceding matches. We can therefore capture the price number and ignore the currency character:

const
  reLookbehind = /(?<=\D)\d+/,
  match        = reLookbehind.exec('$123.89');

console.log( match[0] ); // 123.89

This is a positive lookbehind assertion; a non-digit \D must exist. There’s also a negative lookbehind assertion, which sets that a value must not exist. For example:

const
  reLookbehindNeg = /(?<!\D)\d+/,
  match           = reLookbehind.exec('$123.89');

console.log( match[0] ); // null

Regular Expression s (dotAll) Flag

A regular expression dot . matches any single character except carriage returns. The s flag changes this behavior so line terminators are permitted. For example:

/hello.world/s.test('hello\nworld'); // true

Regular Expression Unicode Property Escapes

Until now, it hasn’t been possible to access Unicode character properties natively in regular expressions. ES2018 adds Unicode property escapes — in the form \p{...} and \P{...} — in regular expressions that have the u (unicode) flag set. For example:

const reGreekSymbol = /\p{Script=Greek}/u;
reGreekSymbol.test('π'); // true

Template Literals Tweak

Finally, all syntactic restrictions related to escape sequences in template literals have been removed.

Previously, a \u started a unicode escape, an \x started a hex escape, and \ followed by a digit started an octal escape. This made it impossible to create certain strings such as a Windows file path C:\uuu\xxx\111. For more details, refer to the MDN template literals documentation.

That’s it for ES2018, but work on ES2019 has already started. Are there any features you’re desperate to see next year?

Frequently Asked Questions about ES2018 Features

What are the new features introduced in ES2018?

ES2018, also known as ECMAScript 2018, introduced several new features to enhance JavaScript’s capabilities. These include asynchronous iteration, Promise.finally(), rest/spread properties, and various RegExp enhancements. Each of these features provides developers with more tools to write efficient and effective code.

How does asynchronous iteration work in ES2018?

Asynchronous iteration is a new feature in ES2018 that allows you to iterate over data that is fetched asynchronously, like data fetched from an API. It uses the ‘for-await-of’ loop, which pauses the loop until the Promise resolves, then continues with the resolved value.

What is the purpose of Promise.finally() in ES2018?

Promise.finally() is a method that allows you to specify final code to run after a Promise is settled, regardless of whether it was fulfilled or rejected. This is particularly useful for cleanup tasks, like stopping a loading spinner after an API call.

What are rest/spread properties in ES2018?

Rest/Spread Properties are a new feature in ES2018 that allow you to collect the remaining own enumerable property keys that are not already picked off by the destructuring pattern. This can be particularly useful when you want to create a new object with some properties of an existing object.

What enhancements were made to RegExp in ES2018?

ES2018 introduced several enhancements to RegExp, including named capture groups, Unicode property escapes, lookbehind assertions, and the s (dotAll) flag. These enhancements provide more powerful pattern matching capabilities in JavaScript.

How can I use the new features of ES2018 in my code?

To use the new features of ES2018, you need to ensure that your development environment supports ES2018. Most modern browsers and Node.js versions support ES2018. You can then start using the new features in your JavaScript code.

Are there any compatibility issues with older versions of ECMAScript when using ES2018?

ES2018 is fully backward compatible with older versions of ECMAScript. However, older browsers or environments may not support all the new features introduced in ES2018. In such cases, you can use transpilers like Babel to convert your ES2018 code into ES5 or ES6 code that is compatible with older environments.

What are the performance implications of using the new features in ES2018?

The performance implications of using the new features in ES2018 can vary depending on the specific feature and how it’s used. However, in general, the new features are designed to improve the efficiency and effectiveness of JavaScript code.

How does ES2018 compare to previous versions like ES6 and ES7?

ES2018 builds on the features introduced in ES6 and ES7, adding new capabilities like asynchronous iteration and Promise.finally(). While ES6 and ES7 introduced major changes like classes and async/await, ES2018 focuses more on enhancing existing features and adding new tools for developers.

What resources are available for learning more about ES2018?

There are many resources available for learning more about ES2018, including the official ECMAScript specification, online tutorials, and blog posts. You can also experiment with the new features in a JavaScript playground or in your own projects.