ES2022 (ECMAScript 2022) Core Features
What are the key features of ES2022? The core ES2022 features include top-level await, public and private instance fields, static class fields, the Object.hasOwn() method, the Array.prototype.at() method, RegExp match indices, and the Error.cause property. These ECMAScript 2022 enhancements significantly improve JavaScript programming patterns.
ES2022 introduced several improvements, including new class features, array and object enhancements, and top-level await.
1. Class Fields and Private Methods
- Public and private fields (
#prefix denotes private). - Private methods and accessors (
#for methods and getters/setters).
Example:
class Person {
name; // Public field
#age; // Private field
constructor(name, age) {
this.name = name;
this.#age = age;
}
#getAge() { // Private method
return this.#age;
}
getInfo() {
return `${this.name} is ${this.#getAge()} years old`;
}
}
const alice = new Person("Alice", 25);
console.log(alice.getInfo()); // ✅ "Alice is 25 years old"
// console.log(alice.#age); // ❌ SyntaxError: Private field '#age' must be declared in an enclosing class
2. Static Class Fields and Methods
- Classes can now define static fields and private static fields.
Example:
class Counter {
static count = 0; // Public static field
static #secret = 42; // Private static field
static increment() {
this.count++;
}
static getSecret() {
return this.#secret;
}
}
Counter.increment();
console.log(Counter.count); // ✅ 1
console.log(Counter.getSecret()); // ✅ 42
3. Object.hasOwn() (Finalized)
- A safer alternative to
Object.prototype.hasOwnProperty().
Example:
const obj = { a: 1 };
console.log(Object.hasOwn(obj, "a")); // ✅ true
console.log(Object.hasOwn(obj, "b")); // ✅ false
4. RegExp Match Indices (/d Flag)
- Provides start and end positions of matches.
Example:
const regex = /hello/d;
const match = regex.exec("hello world");
console.log(match.indices[0]); // ✅ [0, 5] (start and end positions)
5. Error.cause Property
- Allows errors to store their original cause.
Example:
try {
throw new Error("Something went wrong", { cause: "Database connection failed" });
} catch (error) {
console.log(error.message); // ✅ "Something went wrong"
console.log(error.cause); // ✅ "Database connection failed"
}
6. Array.prototype.at()
- Allows negative indexing for arrays and strings.
Example:
const arr = [10, 20, 30];
console.log(arr.at(-1)); // ✅ 30 (last element)
7. Top-Level await in Modules
awaitcan be used outside async functions in ES modules.
Example:
const data = await fetch("https://jsonplaceholder.typicode.com/todos/1").then(res => res.json());
console.log(data);
(Works in ES modules, not in CommonJS.)
Frequently Asked Questions (FAQ)
What is ES2022?
ES2022, or ECMAScript 2022, is a version of the ECMAScript specification that introduces several new features to JavaScript, such as top-level await, new class fields, and the Object.hasOwn() method to improve developer experience and performance.
Is ES2022 supported in all browsers?
Most modern browsers, including Chrome, Firefox, Safari, and Edge, support ES2022 features. However, for older browsers, you may need to use a transpiler like Babel to ensure cross-browser compatibility.
Why is top-level await important in ES2022?
Top-level await allows developers to use the await keyword outside of async functions within ES modules. This simplifies the process of asynchronously loading resources, such as fetching data or dynamically importing modules, right at the top level of a file.