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
await
can 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.)