Exploring the New Features of ECMAScript 2021 (ES12)
Exploring the New Features of ECMAScript 2021 (ES12)
ECMAScript 2021, also known as ES12, introduced several new features and improvements to JavaScript that enhance its functionality and usability. Below is an overview of the key features introduced in this version:
Key Features of ECMAScript 2021
1. Logical Assignment Operators
- Description: Combines logical operators with assignment.
- Examples:
a ||= b
is equivalent toa || (a = b)
a &&= b
is equivalent toa && (a = b)
a ??= b
is equivalent toa ?? (a = b)
2. Numeric Separators
- Description: Allows underscores (
_
) as separators in numeric literals for better readability. - Example:
1_000_000
is easier to read and represents one million.
3. String.prototype.replaceAll()
- Description: A new method to replace all occurrences of a substring in a string.
Example:
const str = "Hello, world! Hello!";
const newStr = str.replaceAll("Hello", "Hi");
console.log(newStr); // "Hi, world! Hi!"
4. Promise.any()
- Description: Returns a promise that resolves when any of the promises in the iterable fulfill, or rejects if all of the given promises are rejected.
Example:
const promise1 = Promise.reject('Error 1');
const promise2 = Promise.resolve('Success 2');
const promise3 = Promise.resolve('Success 3');
Promise.any([promise1, promise2, promise3])
.then(result => console.log(result)); // "Success 2"
5. WeakRefs and FinalizationRegistry
- WeakRefs
- Description: Allows you to hold a weak reference to an object, which does not prevent garbage collection.
- FinalizationRegistry
- Description: Allows you to register a callback that will be called when an object is garbage collected.
Example:
const registry = new FinalizationRegistry((heldValue) => {
console.log(`Cleanup after ${heldValue}`);
});
let obj = { name: "Finalization" };
registry.register(obj, "Object");
obj = null; // Now obj can be garbage collected
Example:
let obj = { name: "Weak Reference" };
let weakRef = new WeakRef(obj);
Conclusion
ECMAScript 2021 has introduced several enhancements that improve JavaScript's functionality and usability. Understanding these new features allows developers to write more efficient and cleaner code, ultimately leading to better applications.