DEV Community

Cover image for New Features Introduced from ES2022
Ambush3
Ambush3

Posted on • Edited on

New Features Introduced from ES2022

As JavaScript keeps involving every year with ECMAScript specifications being released every year since 2015.
Here are a 4 new features coming from ES2022 that you may find useful.

1. Top Level Await

The await keyword previously couldn’t be used outside the async box. Now we can use await without async.

Top-level await enables modules to act as big async functions: With top-level await, ECMAScript Modules (ESM) can await resources, causing other modules who import them to wait before they start evaluating their body.

An example of this:
Image description

2. Error Cause

Errors help us identify the unexpected behavior our applications may produce when things don't go the way they are planned, and help us react accordingly.
Sometimes however, it is hard to determine the root cause of the nested errors, and how to handle them properly.

But now, we can pass the object {cause: err} to the Error constructor to
to show us what caused the error to happen:

Image description

3. RegExp match indices with the d flag

Regular expression matches are patterns that are used to find certain character combinations in strings.
Using String.matchAll and RegExp.exec, we can return a list of matches:

Image description

RegExp.exec will deliver individual results. String.matchAll will return an iterator that can be used to iterate over all the matches.

Thanks to ES2022, we can now use the d flag to specify starting and ending indices of the matches in the RegExp result:

4. .at() method for arrays.

Instead of slicing the array and getting its length until we get what we want. This feature will help you get what you want in a line of code. Perfect for readability and less code.

It provides an easy access to any index of an array or string, either positive or negative:

Image description

Top comments (0)