FOR DEVELOPERS

7 New ES2022 Features That You Should Know

JavaScript  ES2022 Features

The JavaScript family is ever-evolving and has launched new JavaScript features in June 2022. The ES2022 is the 13th edition of features after it was initially launched in 1997. The ES2022 features that reach stage 4 verification are added to the JavaScript family. Reaching stage 4 means that TC-39 has approved the features, cleared the testing stage, and has at least passed two implementations.

These new features align with the language's goals of performance, simplicity, and compatibility. JavaScript's consistent growth underscores its adaptability to the evolving needs of web development, solidifying its position as a cornerstone of modern software engineering.

Let’s get started!

JavaScript features: ES2022 features you should know

As a developer, you must know and understand the new JavaScript features to stay updated. Here is a list of new JavaScript features that are part of the JavaScript family.

Top-level await operator

Asynchronous functions have been used in JavaScript for some time now. In the previous versions, developers could not declare the await keyword outside the asynchronous function. If done, it would show an error message. Now, you can declare the await operator even outside of the asynchronous functions and classes. This solves the synchronization issue. The modules are now capable of waiting for resources that require other modules to import them before rendering the code.

import { fetchData } from './fetchData.js';

const data = await fetchData(); console.log('Fetched data:', data);

In this short example, we directly import the fetchData function and use await at the top level to wait for the data to be fetched.

Class field declarations

Remember, how you always had to invoke a constructor to declare a class field? Not anymore. Now you can declare the class field without calling the constructor.

class Hello {
  field = 0;
  title;
}

const helloInstance = new Hello(); console.log('Field:', helloInstance.field); // Outputs: 0 console.log('Title:', helloInstance.title); // Outputs: undefined

This syntax will not give you an error message now.

Private methods & fields

Looking to declare a private class? You will be able to do this by just adding # as its prefix.

class Hello {
  #field = 0; // Private field
  #title;     // Private field

constructor(title) { this.#title = title; }

publicMethod() { console.log('Private field:', this.#field); console.log('Title:', this.#title); this.#privateMethod(); }

#privateMethod() { console.log('This is a private method'); } }

const helloInstance = new Hello('Private Class Example'); helloInstance.publicMethod();

// Attempting to access private members from outside the class will result in an error // console.log(helloInstance.#field); // Error // helloInstance.#privateMethod(); // Error

Aren’t the new JavaScript features just amazing!

Regexp match indices

This new ES2022 JavaScript feature allows you to use the character “d” to express that you want the starting and ending indexes of the specified matched string. Previously this was not possible. You could only obtain indexing data in the process of string-matching operation.

To retrieve the list of matches

  • You can use Regexp.exec - this will return all the results one after the other
  • String.matchAll. - this will give you an iterator.
const regexPattern = /greeting(\d)/dg; // Regular expression pattern
const exampleString = 'greeting1greeting2'; // Example input string
const matches = [...exampleString.matchAll(regexPattern)]; // Find all matches

console.log('Matches:', matches[0]); // Log the first match

Ergonomic brand checks for private fields

In the previous versions, if you tried to access a public field that wasn’t declared - you would receive an undefined error. Similarly, if you tried to access a private field - you would get an error message.

ES2022 is at your rescue, making your life much easier. By using the “in” operator, you will get the flexibility to check if a field is present in a specific class or not. This feature will be made available even in the private classes.

class UserLogin {
#userName = null;
get #getUser(){if(!this.#userName){throw new Error('No Data!');
}
return this.#userName;
}

static isLogin(user){ return #userName in user && #getUser in user } }

Static class fields & private static methods

Other than the prototype, a static class field cannot be accessed in all instances of a class. The new addition of ES2022 features gives us the freedom to declare static class fields and private static features by using the keyword “static”. Static members belong to the class itself rather than instances of the class, and private static members are accessible only within the class.

Here's an example demonstrating static class fields and private static methods:

class Hello {
  name;
  static #title = 'here'; // Private static field

constructor(name) { this.name = name; }

static getTitle() { return this.#title; // Access private static field } }

const instance1 = new Hello('Instance 1'); const instance2 = new Hello('Instance 2');

console.log(instance1.name); // Output: Instance 1 console.log(instance2.name); // Output: Instance 2

console.log(Hello.#title); // Error: Private static field '#title' is not accessible console.log(Hello.getTitle()); // Output: here

The keyword “static” can be invoked for catching, fixed configurations and cloning objects.

.at() function for indexing

Previously, square brackets were used to index or fetch specific elements in an array. The process was easy unless you had to conduct a backward iteration i.e. required negative indexing. In the case of negative indexing - you had to refer to the string length and index from there. This process has been simplified by the use of the .at() function.

array= [1,2,4,5]
console.log(array[array.length-1]);
console.log(array.at(-1));

In the case of positive indexing, the .at() will function exactly as square brackets. For negative indexing, the .at() function will start the iteration from the end.

Conclusion

JavaScript stands as a dynamic and versatile programming language, offering a stream of annual updates, each introducing valuable features for your projects. Our exploration in this piece centers on the ES2022 features. The anticipation builds for what the future updates will unveil, promising yet another wave of innovation and enhancements. Stay tuned for an exciting journey in the world of JavaScript!

Author

  • 7 New ES2022 Features That You Should Know

    Aditya Sharma

    Aditya is a content writer with 5+ years of experience writing for various industries including Marketing, SaaS, B2B, IT, and Edtech among others. You can find him watching anime or playing games when he’s not writing.

Frequently Asked Questions

ES2022, or ECMAScript 2022, stands as the latest specification defining JavaScript, a fundamental programming language for web development. It encapsulates new features and improvements aimed at optimizing the language for better performance and developer experience.

To start using ES2022 features in your projects, ensure your development environment supports the latest version of JavaScript and update your codebase to leverage the new functionalities, enhancing your project with the latest language enhancements.

The central goals of ES2022 revolve around enhancing developer productivity, refining code maintainability, and ensuring widespread compatibility across various platforms and environments. This involves introducing new functionalities and refining existing ones to meet the evolving needs of developers.

While ES2022 features are widely supported in modern browsers, it's prudent to check for any compatibility concerns using tools like Babel. Employ transpilation techniques if needed to ensure broader browser support, guaranteeing that your application functions seamlessly across a wide range of user environments.

ES2022 significantly enhances JavaScript by offering cleaner syntax, more intuitive functionalities, and improved performance. These improvements lead to more efficient and readable code, positively impacting development workflows and application performance.

ES2022 introduces notable features like "Array.prototype.at," enabling direct access to array elements by index, and "String.prototype.replaceAll," simplifying global string replacement, augmenting the language's capabilities.

View more FAQs
Press

Press

What’s up with Turing? Get the latest news about us here.
Blog

Blog

Know more about remote work. Checkout our blog here.
Contact

Contact

Have any questions? We’d love to hear from you.

Hire remote developers

Tell us the skills you need and we'll find the best developer for you in days, not weeks.