What it is: You can now use await directly at the top level of modules (without needing an async function).
Example:
const data = await fetch('https://api.example.com');
const json = await data.json();
console.log(json);
Use case: Makes working with asynchronous code in modules simpler and cleaner.
What it is: New logical operators combined with assignment, including &&=, ||=, and ??=.
Example:
let a = null;
let b = 42;
a ||= b; // a will be 42 because null is falsy
console.log(a); // 42
Use case: Simplifies conditional assignments.
What it is: Allows for more control over garbage collection. WeakRef provides a reference to an object without preventing it from being garbage collected, and FinalizationRegistry lets you register a callback when an object is garbage collected.
Example:
const obj = { key: 'value' };
const ref = new WeakRef(obj);
const registry = new FinalizationRegistry((heldValue) => {
console.log(`Object with key ${heldValue} is garbage collected`);
});
registry.register(obj, 'key');
Use case: For managing memory more efficiently, especially in long-running applications.
What it is: A new method for handling multiple promises. It returns the first promise that resolves (or throws an error if all promises reject).
Example:
const promise1 = Promise.reject("Error");
const promise2 = Promise.resolve("Success");
Promise.any([promise1, promise2])
.then(result => console.log(result)) // "Success"
.catch(error => console.error(error));
Use case: Helpful when you only need one successful result from multiple promises.
What it is: The ??= operator assigns a value only if the left-hand side is null or undefined.
Example:
let x = null;
x ??= 10; // x will be 10 because it was null
console.log(x); // 10
Use case: Makes it easier to assign default values when a variable is null or undefined.
What it is: The .at() method allows accessing elements in an array using a negative index, similar to how Python and other languages handle array indexing.
Example:
const arr = [1, 2, 3, 4];
console.log(arr.at(-1)); // 4 (last element)
console.log(arr.at(-2)); // 3 (second to last element)
Use case: Simplifies working with arrays from the end.
What it is: You can now define private methods and fields in JavaScript classes using the # syntax.
Example:
class MyClass {
#privateField = 42;
#privateMethod() {
console.log(this.#privateField);
}
publicMethod() {
this.#privateMethod();
}
}
const obj = new MyClass();
obj.publicMethod(); // 42
// obj.#privateField; // SyntaxError: Private field '#privateField' must be declared in an enclosing class
Use case: Encapsulation, preventing access to private data outside the class.
What it is: The .exec() and .match() methods now return the indices of matched substrings.
Example:
const regex = /(\d+)/;
const result = 'hello 123 world'.match(regex);
console.log(result.indices); // [[6, 9]]
Use case: Better handling of substring positions when working with regular expressions.
What it is: The dynamic import() statement now works at the top level, allowing modules to load asynchronously even at the top level.
Example:
import('module.js').then((module) => {
module.doSomething();
});
Use case: Allows more flexibility in module loading.
What it is: New methods like toSorted(), toReversed(), and toSpliced() allow arrays to be transformed without modifying the original array.
Example:
const arr = [1, 2, 3];
const newArr = arr.toSorted();
console.log(newArr); // Sorted array
Use case: Functional programming style transformations where immutability is preferred.
What it is: findLast() and findLastIndex() methods help find elements in an array, starting from the end.
Example:
const arr = [1, 2, 3, 4, 5];
const lastEven = arr.findLast((num) => num % 2 === 0);
console.log(lastEven); // 4
Use case: Finding the last matching element in an array.
What it is: The WeakRef object and FinalizationRegistry are introduced to help manage memory better by allowing cleanup of objects when they are no longer in use.
Use case: Advanced use cases where memory management is critical, such as game development or managing large datasets in memory.
What it is: New methods for creating a sorted array from the existing array without mutating the original array.
Example:
const arr = [3, 1, 4, 2];
const sortedArr = arr.toSorted();
console.log(sortedArr); // [1, 2, 3, 4]
Use case: Helps in keeping arrays immutable while allowing sorting.
These features are some of the highlights of the new updates in JavaScript and are designed to enhance the language's functionality, syntax, and performance, giving developers more power and flexibility in their code.