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
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
5 jQuery.each() Function Examples
5 jQuery.each() Function Examples
Florian RapplJames Hibbard
Implementing User Authentication in React Apps with Appwrite
Implementing User Authentication in React Apps with Appwrite
Yemi Ojedapo
AI-Powered Search Engine With Milvus Vector Database on Vultr
AI-Powered Search Engine With Milvus Vector Database on Vultr
Vultr
Understanding Signals in Django
Understanding Signals in Django
Kabaki Antony
Why React Icons May Be the Only Icon Library You Need
Why React Icons May Be the Only Icon Library You Need
Zain Zaidi
View Transitions in Astro
View Transitions in Astro
Tamas Piros
Getting Started with Content Collections in Astro
Getting Started with Content Collections in Astro
Tamas Piros
What Does the Java Virtual Machine Do All Day?
What Does the Java Virtual Machine Do All Day?
Peter Kessler
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Mayank Singh
Layouts in Astro
Layouts in Astro
Tamas Piros
.NET 8: Blazor Render Modes Explained
.NET 8: Blazor Render Modes Explained
Peter De Tender
Mastering Node CSV
Mastering Node CSV
Dianne Pena
A Beginner’s Guide to SvelteKit
A Beginner’s Guide to SvelteKit
Erik KückelheimSimon Holthausen
Brighten Up Your Astro Site with KwesForms and Rive
Brighten Up Your Astro Site with KwesForms and Rive
Paul Scanlon
Which Programming Language Should I Learn First in 2024?
Which Programming Language Should I Learn First in 2024?
Joel Falconer
Managing PHP Versions with Laravel Herd
Managing PHP Versions with Laravel Herd
Dianne Pena
Accelerating the Cloud: The Final Steps
Accelerating the Cloud: The Final Steps
Dave Neary
An Alphebetized List of MIME Types
An Alphebetized List of MIME Types
Dianne Pena
The Best PHP Frameworks for 2024
The Best PHP Frameworks for 2024
Claudio Ribeiro
11 Best WordPress Themes for Developers & Designers in 2024
11 Best WordPress Themes for Developers & Designers in 2024
SitePoint Sponsors
Top 10 Best WordPress AI Plugins of 2024
Top 10 Best WordPress AI Plugins of 2024
Dianne Pena
20+ Tools for Node.js Development in 2024
20+ Tools for Node.js Development in 2024
Dianne Pena
The Best Figma Plugins to Enhance Your Design Workflow in 2024
The Best Figma Plugins to Enhance Your Design Workflow in 2024
Dianne Pena
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Christopher Collins
Build Your Own AI Tools in Python Using the OpenAI API
Build Your Own AI Tools in Python Using the OpenAI API
Zain Zaidi
The Best React Chart Libraries for Data Visualization in 2024
The Best React Chart Libraries for Data Visualization in 2024
Dianne Pena
7 Free AI Logo Generators to Get Started
7 Free AI Logo Generators to Get Started
Zain Zaidi
Turn Your Vue App into an Offline-ready Progressive Web App
Turn Your Vue App into an Offline-ready Progressive Web App
Imran Alam
Clean Architecture: Theming with Tailwind and CSS Variables
Clean Architecture: Theming with Tailwind and CSS Variables
Emmanuel Onyeyaforo
How to Analyze Large Text Datasets with LangChain and Python
How to Analyze Large Text Datasets with LangChain and Python
Matt Nikonorov
6 Techniques for Conditional Rendering in React, with Examples
6 Techniques for Conditional Rendering in React, with Examples
Yemi Ojedapo
Introducing STRICH: Barcode Scanning for Web Apps
Introducing STRICH: Barcode Scanning for Web Apps
Alex Suzuki
Using Nodemon and Watch in Node.js for Live Restarts
Using Nodemon and Watch in Node.js for Live Restarts
Craig Buckler
Task Automation and Debugging with AI-Powered Tools
Task Automation and Debugging with AI-Powered Tools
Timi Omoyeni
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form