ES2021 (ECMAScript 2021) introduced several new features to JavaScript. Here are the key additions:
1. Numeric Separators (_
)
- Helps improve the readability of large numbers.
- Example:
const billion = 1_000_000_000; // Same as 1000000000 const bytes = 0xFF_FF_FF_FF; // Hexadecimal format
2. String replaceAll()
- Adds a built-in way to replace all occurrences of a substring.
- Example:
const text = "hello world, world!"; console.log(text.replaceAll("world", "JS")); // Output: "hello JS, JS!"
3. Promise any()
- Similar to
Promise.race()
, but resolves with the first fulfilled promise (ignores rejected ones). - If all promises reject, it throws an
AggregateError
. - Example:
const p1 = Promise.reject("Error 1"); const p2 = new Promise(resolve => setTimeout(resolve, 100, "Success!")); const p3 = Promise.reject("Error 2"); Promise.any([p1, p2, p3]).then(console.log).catch(console.error); // Output: "Success!"
4. WeakRefs and FinalizationRegistry
- Allows for weak references to objects, preventing memory leaks in certain cases.
- Used for caching and cleaning up resources.
- Example:
-
let obj = { name: "Alice" }; const weakRef = new WeakRef(obj); obj = null;
// The object can now be garbage collected
const registry = new FinalizationRegistry((heldValue) => { console.log(`${heldValue} was garbage collected`); }); registry.register(weakRef.deref(), "Alice");
5. Logical Assignment Operators (&&=
, ||=
, ??=
)
- Shorter syntax for conditional assignments.
&&=
(AND assignment):let x = true; x &&= false; // x becomes false
||=
(OR assignment):let y = null; y ||= "default"; // y becomes "default"
??=
(Nullish coalescing assignment):let z = undefined; z ??= "fallback"; // z becomes "fallback"
6. Object.hasOwn()
- A safer alternative to
Object.prototype.hasOwnProperty
, avoiding prototype chain issues. - Example:
const obj = { a: 1 }; console.log(Object.hasOwn(obj, "a")); // true console.log(Object.hasOwn(obj, "b")); // false
Summary of ES2021 Features:
Feature | Description |
---|---|
Numeric Separators (_ ) | Improves number readability |
String.prototype.replaceAll() | Replaces all occurrences of a substring |
Promise.any() | Resolves with the first fulfilled promise |
WeakRefs & FinalizationRegistry | Enables weak references for memory management |
Logical Assignment Operators (&&= , ` | |
Object.hasOwn() | A safer alternative to hasOwnProperty |