What’s New in ES2023?

ECMAScript 2023 (ES14) introduced several new features to improve JavaScript’s functionality and usability.

Here are the key updates with examples:

Array Find From Last

Array.prototype.findLast and Array.prototype.findLastIndex allow searching arrays from the end.

For example, we write:

const array = [1, 2, 3, 4, 5];
const found = array.findLast((element) => element % 2 === 1);
console.log(found); // 5

const foundIndex = array.findLastIndex((element) => element % 2 === 1);
console.log(foundIndex); // 4

Change Array by Copy

New methods like toSorted, toReversed, toSpliced, and with create modified copies of arrays without changing the original.

For instance, we write

const array = [3, 1, 4, 1, 5];
const sorted = array.toSorted();
console.log(sorted); // [1, 1, 3, 4, 5]
console.log(array); // [3, 1, 4, 1, 5]

const reversed = array.toReversed();
console.log(reversed); // [5, 1, 4, 1, 3]

Symbols as WeakMap Keys

Symbols can now be used as keys in WeakMaps and WeakSets.

For example:

const wm = new WeakMap();
const sym = Symbol("key");
wm.set(sym, "value");
console.log(wm.get(sym)); // 'value'

Hashbang Grammar

JavaScript now supports hashbangs (#!) for use in scripts, improving interoperability with Unix-like systems.

For example, we write:

#!/usr/bin/env node
console.log('Hello, world!');

Promise with Any

Promise.any returns the first fulfilled promise from a set of promises, or rejects if all of them reject.

For instance, we write

const p1 = Promise.reject("Error 1");
const p2 = Promise.resolve("Success");
const p3 = Promise.reject("Error 2");

Promise.any([p1, p2, p3])
  .then((value) => console.log(value)) // 'Success'
  .catch((error) => console.error(error));

WeakRef and FinalizationRegistry

WeakRef provides a way to hold weak references to objects, and FinalizationRegistry allows registering cleanup operations to be performed after an object is garbage collected.

Example:

let target = { name: "target" };
const weakRef = new WeakRef(target);

const registry = new FinalizationRegistry((heldValue) => {
  console.log(`Cleanup after ${heldValue}`);
});

registry.register(target, "target");

target = null; // `target` is now eligible for garbage collection

Temporal

The Temporal API offers a modern way to handle dates and times, providing more accurate and intuitive methods than the existing Date object.

Example:

const now = Temporal.Now.plainDateTimeISO();
console.log(now.toString()); // e.g., '2023-07-01T12:34:56'

const birthday = Temporal.PlainDate.from("2000-01-01");
const age = now.since(birthday);
console.log(`You are ${age.years} years old.`); // 'You are 23 years old.'

These updates in ES2023 bring more flexibility, modern functionality, and improved performance to JavaScript development.