What’s New in ES2018

Share this article

What’s New in ES2018

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.

Craig BucklerCraig Buckler
View Author

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

es2018es9learn-modernjsmodernjsmodernjs-hub
Share this article
Read Next
A Deep Dive into Building Enterprise grade Generative AI Solutions
A Deep Dive into Building Enterprise grade Generative AI Solutions
Suvoraj Biswas
LocalXpose: The Most Useful Tool for Developers to Share Localhost Online
LocalXpose: The Most Useful Tool for Developers to Share Localhost Online
SitePoint Sponsors
8 AI Tips for Web Developers (and Their Careers)
8 AI Tips for Web Developers (and Their Careers)
Jens Oliver Meiert
How to Make a Simple JavaScript Quiz
How to Make a Simple JavaScript Quiz
Yaphi BerhanuJames Hibbard
Best React UI Component Libraries
Best React UI Component Libraries
Kaarle Varkki
Windows Subsystem for Linux 2 (WSL2): The Complete Tutorial for Windows 10 & 11
Windows Subsystem for Linux 2 (WSL2): The Complete Tutorial for Windows 10 & 11
Craig Buckler
Automating Vultr Cloud Infrastructure with Terraform
Automating Vultr Cloud Infrastructure with Terraform
Vultr
Advanced Web Deployment With Plesk on Vultr
Advanced Web Deployment With Plesk on Vultr
Vultr
Building A 300 Channel Video Encoding Server
Building A 300 Channel Video Encoding Server
John O’Neill
Five Ways to Lazy Load Images for Better Website Performance
Five Ways to Lazy Load Images for Better Website Performance
Maria Antonietta Perna
Building a Telemedicine Platform with AI-Powered Diagnostics Using Vultr
Building a Telemedicine Platform with AI-Powered Diagnostics Using Vultr
Vultr
Create a Toggle Switch in React as a Reusable Component
Create a Toggle Switch in React as a Reusable Component
Praveen KumarMichael Wanyoike
Comparing Docker and Podman: A Guide to Container Management Tools
Comparing Docker and Podman: A Guide to Container Management Tools
Vultr
How to Deploy Flask Applications on Vultr
How to Deploy Flask Applications on Vultr
Vultr
A Comprehensive Guide to Understanding TypeScript Record Type
A Comprehensive Guide to Understanding TypeScript Record Type
Emmanuel Onyeyaforo
Top 7 High-Paying Affiliate Programs for Developers and Content Creators
Top 7 High-Paying Affiliate Programs for Developers and Content Creators
SitePoint Sponsors
How to integrate artificial intelligence into office software: the ONLYOFFICE Docs case study
How to integrate artificial intelligence into office software: the ONLYOFFICE Docs case study
SitePoint Sponsors
Momento Migrates Object Cache as a Service to Ampere Altra
Momento Migrates Object Cache as a Service to Ampere Altra
Dave Neary
Dev Hackathon: Reusable Creativity on Wix Studio
Dev Hackathon: Reusable Creativity on Wix Studio
SitePoint Sponsors
10 Amazing Web Developer Resume Examples for Different Web Dev Specializations
10 Amazing Web Developer Resume Examples for Different Web Dev Specializations
SitePoint Sponsors
How to Build Lightning Fast Surveys with Next.js and SurveyJS
How to Build Lightning Fast Surveys with Next.js and SurveyJS
Gavin Henderson
45 Visual Studio Code Shortcuts for Boosting Your Productivity
45 Visual Studio Code Shortcuts for Boosting Your Productivity
Shahed Nasser
Google Cloud Is the New Way to the Cloud
Google Cloud Is the New Way to the Cloud
SitePoint Sponsors
Understanding Vultr Content Delivery Networks (CDNs)
Understanding Vultr Content Delivery Networks (CDNs)
Vultr
Effortless Content Publishing: A Developer’s Guide to Adobe Experience Manager
Effortless Content Publishing: A Developer’s Guide to Adobe Experience Manager
SitePoint Sponsors
From Idea to Prototype in Minutes: Claude Sonnet 3.5
From Idea to Prototype in Minutes: Claude Sonnet 3.5
Zain Zaidi
Essential Plugins for WordPress Developers: Top Picks for 2024
Essential Plugins for WordPress Developers: Top Picks for 2024
SitePoint Sponsors
WebAssembly vs JavaScript: A Comparison
WebAssembly vs JavaScript: A Comparison
Kaan Güner
The Functional Depth of Docker and Docker Compose
The Functional Depth of Docker and Docker Compose
Vultr
How Top HR Agencies Build Trust Through Logo Designs
How Top HR Agencies Build Trust Through Logo Designs
Evan Brown
Leveraging Progressive Web Apps (PWAs) for Enhanced Mobile User Engagement
Leveraging Progressive Web Apps (PWAs) for Enhanced Mobile User Engagement
SitePoint Sponsors
10 Artificial Intelligence APIs for Developers
10 Artificial Intelligence APIs for Developers
SitePoint Sponsors
The Ultimate Guide to Navigating SQL Server With SQLCMD
The Ultimate Guide to Navigating SQL Server With SQLCMD
Nisarg Upadhyay
Retrieval-augmented Generation: Revolution or Overpromise?
Retrieval-augmented Generation: Revolution or Overpromise?
Kateryna ReshetiloOlexandr Moklyak
How to Deploy Apache Airflow on Vultr Using Anaconda
How to Deploy Apache Airflow on Vultr Using Anaconda
Vultr
Cloud Native: How Ampere Is Improving Nightly Arm64 Builds
Cloud Native: How Ampere Is Improving Nightly Arm64 Builds
Dave NearyAaron Williams
How to Create Content in WordPress with AI
How to Create Content in WordPress with AI
Çağdaş Dağ
A Beginner’s Guide to Setting Up a Project in Laravel
A Beginner’s Guide to Setting Up a Project in Laravel
Claudio Ribeiro
Enhancing DevSecOps Workflows with Generative AI: A Comprehensive Guide
Enhancing DevSecOps Workflows with Generative AI: A Comprehensive Guide
Gitlab
Creating Fluid Typography with the CSS clamp() Function
Creating Fluid Typography with the CSS clamp() Function
Daine Mawer
Comparing Full Stack and Headless CMS Platforms
Comparing Full Stack and Headless CMS Platforms
Vultr
7 Easy Ways to Make a Magento 2 Website Faster
7 Easy Ways to Make a Magento 2 Website Faster
Konstantin Gerasimov
Powerful React Form Builders to Consider in 2024
Powerful React Form Builders to Consider in 2024
Femi Akinyemi
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Ralph Mason
Sending Email Using Node.js
Sending Email Using Node.js
Craig Buckler
Creating a Navbar in React
Creating a Navbar in React
Vidura Senevirathne
A Complete Guide to CSS Logical Properties, with Cheat Sheet
A Complete Guide to CSS Logical Properties, with Cheat Sheet
Ralph Mason
Using JSON Web Tokens with Node.js
Using JSON Web Tokens with Node.js
Lakindu Hewawasam
How to Build a Simple Web Server with Node.js
How to Build a Simple Web Server with Node.js
Chameera Dulanga
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Beloslava Petrova
Crafting Interactive Scatter Plots with Plotly
Crafting Interactive Scatter Plots with Plotly
Binara Prabhanga
GenAI: How to Reduce Cost with Prompt Compression Techniques
GenAI: How to Reduce Cost with Prompt Compression Techniques
Suvoraj Biswas
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
Aurelio De RosaMaria Antonietta Perna
Quick Tip: How to Align Column Rows with CSS Subgrid
Quick Tip: How to Align Column Rows with CSS Subgrid
Ralph Mason
15 Top Web Design Tools & Resources To Try in 2024
15 Top Web Design Tools & Resources To Try in 2024
SitePoint Sponsors
7 Simple Rules for Better Data Visualization
7 Simple Rules for Better Data Visualization
Mariia Merkulova
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
SitePoint Team
Best Programming Language for AI
Best Programming Language for AI
Lucero del Alba
Quick Tip: How to Add Gradient Effects and Patterns to Text
Quick Tip: How to Add Gradient Effects and Patterns to Text
Ralph Mason
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Vultr
How to Optimize Website Content for Featured Snippets
How to Optimize Website Content for Featured Snippets
Dipen Visavadiya
Psychology and UX: Decoding the Science Behind User Clicks
Psychology and UX: Decoding the Science Behind User Clicks
Tanya Kumari
Build a Full-stack App with Node.js and htmx
Build a Full-stack App with Node.js and htmx
James Hibbard
Digital Transformation with AI: The Benefits and Challenges
Digital Transformation with AI: The Benefits and Challenges
Priyanka Prajapat
Quick Tip: Creating a Date Picker in React
Quick Tip: Creating a Date Picker in React
Dianne Pena
How to Create Interactive Animations Using React Spring
How to Create Interactive Animations Using React Spring
Yemi Ojedapo
10 Reasons to Love Google Docs
10 Reasons to Love Google Docs
Joshua KrausZain Zaidi
How to Use Magento 2 for International Ecommerce Success
How to Use Magento 2 for International Ecommerce Success
Mitul Patel
5 Exciting New JavaScript Features in 2024
5 Exciting New JavaScript Features in 2024
Olivia GibsonDarren Jones
Tools and Strategies for Efficient Web Project Management
Tools and Strategies for Efficient Web Project Management
Juliet Ofoegbu
Choosing the Best WordPress CRM Plugin for Your Business
Choosing the Best WordPress CRM Plugin for Your Business
Neve Wilkinson
ChatGPT Plugins for Marketing Success
ChatGPT Plugins for Marketing Success
Neil Jordan
Managing Static Files in Django: A Comprehensive Guide
Managing Static Files in Django: A Comprehensive Guide
Kabaki Antony
The Ultimate Guide to Choosing the Best React Website Builder
The Ultimate Guide to Choosing the Best React Website Builder
Dianne Pena
Exploring the Creative Power of CSS Filters and Blending
Exploring the Creative Power of CSS Filters and Blending
Joan Ayebola
How to Use WebSockets in Node.js to Create Real-time Apps
How to Use WebSockets in Node.js to Create Real-time Apps
Craig Buckler
Best Node.js Framework Choices for Modern App Development
Best Node.js Framework Choices for Modern App Development
Dianne Pena
SaaS Boilerplates: What They Are, And 10 of the Best
SaaS Boilerplates: What They Are, And 10 of the Best
Zain Zaidi
Understanding Cookies and Sessions in React
Understanding Cookies and Sessions in React
Blessing Ene Anyebe
Enhanced Internationalization (i18n) in Next.js 14
Enhanced Internationalization (i18n) in Next.js 14
Emmanuel Onyeyaforo
Essential React Native Performance Tips and Tricks
Essential React Native Performance Tips and Tricks
Shaik Mukthahar
How to Use Server-sent Events in Node.js
How to Use Server-sent Events in Node.js
Craig Buckler
Five Simple Ways to Boost a WooCommerce Site’s Performance
Five Simple Ways to Boost a WooCommerce Site’s Performance
Palash Ghosh
Elevate Your Online Store with Top WooCommerce Plugins
Elevate Your Online Store with Top WooCommerce Plugins
Dianne Pena
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Dianne Pena
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
Vultr
Enhance Your React Apps with ShadCn Utilities and Components
Enhance Your React Apps with ShadCn Utilities and Components
David Jaja
10 Best Create React App Alternatives for Different Use Cases
10 Best Create React App Alternatives for Different Use Cases
Zain Zaidi
Control Lazy Load, Infinite Scroll and Animations in React
Control Lazy Load, Infinite Scroll and Animations in React
Blessing Ene Anyebe
Building a Research Assistant Tool with AI and JavaScript
Building a Research Assistant Tool with AI and JavaScript
Mahmud Adeleye
Understanding React useEffect
Understanding React useEffect
Dianne Pena
Web Design Trends to Watch in 2024
Web Design Trends to Watch in 2024
Juliet Ofoegbu
Building a 3D Card Flip Animation with CSS Houdini
Building a 3D Card Flip Animation with CSS Houdini
Fred Zugs
How to Use ChatGPT in an Unavailable Country
How to Use ChatGPT in an Unavailable Country
Dianne Pena
An Introduction to Node.js Multithreading
An Introduction to Node.js Multithreading
Craig Buckler
How to Boost WordPress Security and Protect Your SEO Ranking
How to Boost WordPress Security and Protect Your SEO Ranking
Jaya Iyer
Understanding How ChatGPT Maintains Context
Understanding How ChatGPT Maintains Context
Dianne Pena
Building Interactive Data Visualizations with D3.js and React
Building Interactive Data Visualizations with D3.js and React
Oluwabusayo Jacobs
JavaScript vs Python: Which One Should You Learn First?
JavaScript vs Python: Which One Should You Learn First?
Olivia GibsonDarren Jones
13 Best Books, Courses and Communities for Learning React
13 Best Books, Courses and Communities for Learning React
Zain Zaidi
Get the freshest news and resources for developers, designers and digital creators in your inbox each week