Discover the most recent advancements in JavaScript, particularly with the ES2023 (ECMAScript 2023) specification. This guide covers new features, improvements, and practical uses.
The Array.findLast()
and Array.findLastIndex()
methods provide ways to access the last element in an array that meets a specific condition:
const numbers = [5, 12, 50, 130, 44];
const found = numbers.findLast(n => n < 50); // 44
const foundIndex = numbers.findLastIndex(n => n < 50); // 4
The Array.prototype.at()
method allows you to access elements from the end of an array using negative indices:
const arr = [1, 2, 3, 4, 5];
console.log(arr.at(-1)); // 5
console.log(arr.at(-2)); // 4
The Object.hasOwn()
method provides a concise way to check if an object has a specific property:
const obj = { a: 1, b: 2 };
console.log(Object.hasOwn(obj, 'a')); // true
console.log(Object.hasOwn(obj, 'c')); // false
With top-level await, you can use await
directly in modules without needing to wrap it in an async function:
// Example with top-level await
const data = await fetch('https://api.example.com/data');
const json = await data.json();
console.log(json);
These new features help manage memory more effectively:
// Using WeakRef
let obj = { name: 'example' };
let weakRef = new WeakRef(obj);
obj = null; // The object can be garbage collected
// Using FinalizationRegistry
const registry = new FinalizationRegistry((heldValue) => {
console.log(`Object with held value ${heldValue} has been garbage collected`);
});
let myObject = { name: 'example' };
registry.register(myObject, 'some value');
myObject = null; // Will trigger the finalization callback when garbage collected
These operators combine logical operations with assignment:
let x = true;
x &&= false; // x is now false
let y = null;
y ??= 'default'; // y is now 'default'
Enhancements have been made to WeakMap
and WeakSet
, making them more versatile:
const weakMap = new WeakMap();
const obj = {};
weakMap.set(obj, 'value');
console.log(weakMap.get(obj)); // 'value'
Provides start and end indices for matched results in regular expressions:
const regex = /(foo)/;
const result = 'foobar'.matchAll(regex);
for (const match of result) {
console.log(match.indices); // Outputs start and end indices of matches
}
This method ensures that the string is well-formed in terms of Unicode characters:
const str = 'hello';
console.log(str.isWellFormed()); // true
The Intl.DisplayNames
API allows for localized display names of languages, regions, and scripts:
const displayNames = new Intl.DisplayNames(['en'], { type: 'region' });
console.log(displayNames.of('US')); // 'United States'
These features highlight the ongoing evolution of JavaScript, making it more powerful and versatile for modern web development.
Published By: Krishanu Jadiya
Updated at: 2024-08-03 16:35:49