ES2023 New JavaScript Features You Can Use in WordPress Development

ES2023 array methods in WordPress scripts: toSorted, toReversed, with, findLast

sort(), reverse() and splice() change the array they are called on. When that array is shared state, for example the list a component renders or the value in a store, a “just for display” sort silently changes the data for every other part of the script. ES2023 added copying versions of these methods and two search methods from the end of an array.

Problem: A notification panel in the WordPress admin shows the newest entries first with notifications.reverse(). After the panel is opened twice, the order flips back, and the “mark as read” code marks the wrong entry because indexes changed.

Solution: Use toReversed(), toSorted(), toSpliced() and with(), which return a new array and leave the original unchanged, and findLast() / findLastIndex() instead of reversing an array just to search it from the end.

Copy instead of change

const notifications = [
    { id: 1, text: 'Plugin activated', time: 1717000000, read: true },
    { id: 2, text: 'Update available', time: 1717001000, read: false },
    { id: 3, text: 'Backup completed', time: 1717002000, read: false },
];

const newestFirst = notifications.toReversed();
const byTime = notifications.toSorted( ( a, b ) => b.time - a.time );
const withoutSecond = notifications.toSpliced( 1, 1 );
const withNew = notifications.toSpliced( 0, 0, { id: 4, text: 'Cache cleared', time: Date.now() / 1000, read: false } );
const secondRead = notifications.with( 1, { ...notifications[ 1 ], read: true } );

console.log( notifications[ 0 ].id ); // still 1: the original is unchanged
  • toReversed() = reverse() on a copy.
  • toSorted( compareFn ) = sort() on a copy, with the same compare function.
  • toSpliced( start, deleteCount, ...items ) returns the new array, not the removed elements as splice() does.
  • with( index, value ) replaces one element; negative indexes count from the end, as in at().

The copies are shallow: the objects inside are the same objects. That is why with() above gets a new object with the spread operator instead of changing notifications[ 1 ].read.

Search from the end

const lastUnread = notifications.findLast( ( n ) => ! n.read );          // { id: 3, ... }
const lastUnreadIndex = notifications.findLastIndex( ( n ) => ! n.read ); // 2

// before: [ ...notifications ].reverse().find( ... ), with a copy just to search

findLast() returns undefined and findLastIndex() returns -1 when nothing matches, like their forward versions.

In a render function

function haVisibleNotifications( all, { showRead = false } = {} ) {
    return all
        .filter( ( n ) => showRead || ! n.read )
        .toSorted( ( a, b ) => b.time - a.time )
        .slice( 0, 20 );
}

Here filter() already returns a new array, so a plain sort() would be safe too. toSorted() is still the better habit: the function stays correct when somebody removes the filter() later. With a store that notifies subscribers only when a key gets a new value, the copying methods are what make the change visible: state.items = state.items.toSpliced( 0, 0, item ) assigns a new array, while state.items.unshift( item ) would change the old one unnoticed. A store of that kind: reactive store with Proxy.

Also in ES2023

Arrays are not the only change. A script file can start with a hashbang line (#!/usr/bin/env node), which matters for Node.js tooling, and symbols can be used as keys in WeakMap. For theme and plugin code in the browser, the array methods are the part that is used every day.

NOTE: toSorted(), toReversed(), toSpliced() and with() work in Chrome 110, Safari 16 and Firefox 115 (July 2023); findLast() is older (Chrome 97, Safari 15.4, Firefox 104). With @wordpress/scripts the code is transpiled by Babel, but new methods of built-in objects are not added by Babel; for older browsers they need a polyfill such as core-js. They are also available in Node.js 20 for build scripts.