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:
- The array includes() method, which returns true or false when a value is contained in an array, and
- The
a ** b
exponentiation operator, which is identical toMath.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 pairsObject.entries()
, which returns an array of sub-arrays containing the names and values in an objectObject.getOwnPropertyDescriptors()
to return an object defining property descriptors for own properties of another object (.value
,.writable
,.get
,.set
,.configurable
,.enumerable
)padStart()
andpadEnd()
, both elements of string padding- trailing commas on object definitions, array declarations and function parameter lists
SharedArrayBuffer
andAtomics
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?