-
Object.fromEntries()
method: This method creates an object from a given list of key-value pairs.
const entries - [['foo', 1], ['bar', 2]];
const obj = Object.fromEntries(entries);
console.log(obj);
// {foo: 1, bar: 2}
-
String.prototype.matchAll()
method: This methods returns an iterator containing all the matches of a regular expression in a string.
const str = 'Hello, world!';
const regex = /\w+/g;
const matches = str.matchAll(regex);
console.log(matches);
//Iterator { 'h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'}
-
Promise.any()
method: This method returns a promise that is fulfilled with the first fulfilled promise in an iterable of promises.
const p1 = new Promise((resolve) => setTimeout(() => resolve('p1'), 100));
const p2 = new Promise((resolve) => setTimeout(() => resolve('p2'), 200));
const p3 = new Promise((resolve) => setTimeout(() => resolve('p3'), 300));
Promise.any([p1, p2, p3]).then(result => console.log(result));
// 'p1'
-
globalThis
property: This property provides a way to access the global object in a consistent way, regardless of the environment (browser or Node.js).
console.log(globalThis);
// Window {...} in browser, global in Node.js
-
Optional chaining
: This operator allows you to access a property of an object, even if the object or any of its preceding objects in the chain are null or undefined.
let obj = { a: { b: { c: "hello" } } };
console.log(obj?.a?.b?.c); // prints "hello"
-
Nullish coalescing
: This operator allows you to provide a default value for a variable only if it is null or undefined.
let x = null;
console.log(x ?? "default"); // prints "default"
-
Dynamic import()
: This method allows you to dynamically load modules at runtime, instead of loading all modules at the start of the program.
async function loadModule() {
const module = await import('./module.js');
// Use the module
}
-
WeakRef and FinalizationRegistry
: These are two new types that allow you to create weak references to objects, and to register callbacks to be called when an object is garbage collected.
const obj = {};
const weakRef = new WeakRef(obj);
console.log(weakRef.deref()); // prints the object
-
Private methods and fields
: ECMAScript 2021 introduces syntax for declaring private methods and fields in classes. Private methods and fields can only be accessed within the class.
class MyClass {
#privateField = "I am private";
#privateMethod() {
console.log("I am a private method");
}
publicMethod() {
console.log(this.#privateField);
this.#privateMethod();
}
}
These are additional features that ECMAScript 2021 introduces, it's important to note that some of them may not be supported on all JavaScript engines yet. Follow official documents for more features ECMAScript.
Top comments (0)