See the ES2021 standard for full specification of the ECMAScript 12 language.
ES12 includes the following new feature proposals:
- String.prototype.replaceAll()
- Promise.any()
- WeakRef and FinalizationRegistry
- Logical assignment operators
- Numeric separators
- Array.prototype.at()
- Private fields and methods
String.prototype.replaceAll()
method replaces all instances of a specified substring in a string with a replacement string.
Example:
const str = "Hello, World!";
const newStr = str.replaceAll("o", "x");
console.log(newStr); // "Hellx, Wxrld!"
Promise.any
method returns a promise that is fulfilled with the value of the first promise in an iterable that fulfills.
Example:
const promises = [
Promise.reject("Error 1"),
Promise.resolve("Success 1"),
Promise.resolve("Success 2"),
Promise.reject("Error 2"),
];
Promise.any(promises)
.then((result) => console.log(result))
.catch((error) => console.log(error));
// Output: "Success 1"
WeakRef and FinalizationRegistry new APIs allow developers to create weak references to objects and register finalizers to be executed when an object is garbage collected.
Example:
const object = { foo: "bar" };
const weakRef = new WeakRef(object);
const finalizationRegistry = new FinalizationRegistry((value) => {
console.log("Object has been garbage collected:", value);
});
finalizationRegistry.register(object, "my value");
object = null;
Logical assignment operators (||=, &&=, ??=) - These operators combine logical operators with assignment, allowing for more concise code.
Example:
let x = 10;
x ||= 20; // equivalent to x = x || 20;
console.log(x); // Output: 10
let y = null;
y ??= "default value"; // equivalent to y = y ?? "default value";
console.log(y); // Output: "default value"
Numeric separators
feature allows developers to use underscores as separators in numeric literals to improve readability.
Example:
const billion = 1_000_000_000;
console.log(billion); // Output: 1000000000
Array.prototype.at()
method returns the element at a specified index in an array.
Example:
const arr = ["a", "b", "c", "d", "e"];
console.log(arr.at(2)); // Output: "c"
Private fields and methods - This feature allows developers to define private fields and methods in classes, which are not accessible outside the class.
Example:
class Example {
#privateField = "private";