What are ES2022 - ES13 features?
1. Top-Level await
Previously, the await
keyword could only be used within asynchronous functions. ES13 allows the use of await
at the top level of modules, enabling asynchronous operations without wrapping them in an async
function.
2. Class Field Declarations
ES13 allows developers to define and initialize class fields directly within the class body, improving code readability and organization.
class Person {
name = 'Alice';
age = 30;
}
3. Private Class Fields and Methods
By prefixing class fields and methods with a #
, ES13 introduces true encapsulation, making them private and inaccessible from outside the class.
class User {
#password = 'secret';
#encryptPassword() {
// encryption logic
}
}
const user = new User();
console.log(user.#password); // SyntaxError
4. Static Class Fields and Methods
ES13 allows the declaration of static fields and methods directly within the class body, accessible without instantiating the class.
class MathUtils {
static pi = 3.14159;
static calculateCircumference(radius) {
return 2 * MathUtils.pi * radius;
}
}
console.log(MathUtils.calculateCircumference(5)); // 31.4159
5. Class Static Initialization Blocks
Static initialization blocks allow for complex static initialization within classes, providing a way to execute statements during class definition.
class Configuration {
static settings;
static {
Configuration.settings = loadSettings();
}
}
6. at()
Method for Indexing
The at()
method provides a way to access elements of arrays, strings, and typed arrays using positive or negative indices.
const arr = [10, 20, 30, 40];
console.log(arr.at(1)); // 20
console.log(arr.at(-1)); // 40
7. RegExp Match Indices
The addition of the d
flag in regular expressions provides match indices, allowing developers to retrieve the start and end positions of matches.
const regex = /foo/d;
const match = regex.exec("foo bar foo");
console.log(match.indices); // [[0, 3]]
8. Object.hasOwn()
Method
The Object.hasOwn()
method offers a more concise way to check if an object has a specific property, replacing the need for Object.prototype.hasOwnProperty.call()
const obj = { key: 'value' };
console.log(Object.hasOwn(obj, 'key')); // true
9. Error Cause
ES13 introduces the cause
property for errors, allowing developers to provide additional context when throwing exceptions.
try {
throw new Error("Primary error", { cause: "Additional context" });
} catch (error) {
console.log(error.message); // "Primary error"
console.log(error.cause); // "Additional context"
}