toSorted(), toReversed() and toSpliced() - New Functional Methods! ES2023

ES2023 brings many nice new features, but today I want to cover the most useful things to my workflow: toSorted(), toReversed() and toSpliced().

If you have used sort(), reverse(), and slice() methods in JavaScript, you might or might not be aware that those methods can often lead to side effects because those methods mutate the array in place.

If you are like me, you want your code to be predictable and functional; these new methods in JS are a nice way to save a few lines of code (or avoid bugs if you forget about the nature of the old methods).

In this article, I'll show a short example of each so you can start with them. 👇

All of the functions use the same syntax as their predecessors, with the only difference being that they return a changed copy of the array that you called the method on.

toSorted()

If you don't remember your sort syntax or how to use it, you can check out the MDN docs here.

const arr = [9, 4, 5, 1, 2, 0];

console.log(arr.toSorted());
// Output 👉 [0, 1, 2, 4, 5, 9]

console.log(arr.toSorted((a, b) =>  a - b));
// Output 👉 [0, 1, 2, 4, 5, 9]

console.log(arr.toSorted((a, b) => b - a));
// Output 👉 [9, 5, 4, 2, 1, 0]

toReversed()

This one is as easy as it gets:

const arr = [1, 2, 3, 4];

console.log(arr.toReversed());
// Output 👉 [4, 3, 2, 1]

toSpliced()

The toSpliced() method works again similarly to the splice() method syntax-wise.

And as a reminder, that is - it returns a new array with some elements removed and/or replaced at a given index.

Since it's one I always mixup with slice here's a tiny recap of it's syntax:

toSpliced(start, deleteCount, itemToAdd, moreItemsToAdd, itemEtc)

Now an example:

const users = ["niallmaher", "johndoe", "ccobo", "mrhelloworld"];

// Remove 1 item at index 1
console.log(users.toSpliced(1, 1))
// Output 👉 ['niallmaher', 'ccobo', 'mrhelloworld']

// Remove 1 item and replace at index 1
console.log(users.toSpliced(1, 1, "notjohn"))
// Output 👉 ['niallmaher', 'notjohn', 'ccobo', 'mrhelloworld']

Compatibility

It's important to note these methods are so new that they might not be supported everywhere. You might still need to create a polyfill to ensure you get coverage everywhere. Here's the compatibility at the time of publishing this article:

Browser compatibility chart from Mozilla

You can check if there have been any compatibility updates here.


Follow me on Twitter or connect on LinkedIn.

🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉

Es2023ArrayJavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.