![ES12](https://codesanitize.com/wp-content/uploads/2024/01/ES12.png)
Master JavaScript’s Latest Updates: A Guide to ES12 (ECMAScript 2021):
Here are the key features introduced in ES12 (ECMAScript 2021), with detailed descriptions and examples:
1. Logical Assignment Operators:
- ??= (Nullish Coalescing Assignment): Assigns a value only if the left-hand side is
null
orundefined
.
JavaScript
let name = null;
name ??= "John"; // name becomes "John"
- &&= (Logical AND Assignment): Assigns a value only if the left-hand side is truthy.
JavaScript
let enabled = true;
enabled &&= false; // enabled remains true
- ||= (Logical OR Assignment): Assigns a value only if the left-hand side is falsy.
JavaScript
let message = "";
message ||= "Hello!"; // message becomes "Hello!"
2. String.prototype.replaceAll():
- Replaces all occurrences of a substring with another substring.
JavaScript
const text = "Hello, world!";
const newText = text.replaceAll("o", "a"); // "Halla, warld!"
3. Numeric Separators:
- Underscores (
_
) can be used to improve readability of large numbers.
JavaScript
const largeNumber = 123_456_789; // Same as 123456789
4. Promise.any():
- Settles as soon as one of the provided Promises resolves, returning its value.
JavaScript
Promise.any([
fetch('/data1'),
fetch('/data2'),
]).then(result => {
// Handle the first resolved Promise's result
});
5. WeakRef:
- Creates weak references to objects, allowing the garbage collector to reclaim them if no strong references exist.
JavaScript
const weakRef = new WeakRef(object);
6. FinalizationRegistry:
- Notifies you when a weakly referenced object is about to be garbage collected.
JavaScript
const registry = new FinalizationRegistry((heldValue) => {
// Callback when object is collected
});
7. AggregateError:
- A new error type that groups multiple errors together.
JavaScript
const errors = [new Error("Error 1"), new Error("Error 2")];
throw new AggregateError(errors);
Note: These features continue JavaScript’s evolution towards more concise syntax, improved error handling, and better control over memory management.