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:
If you have used
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.
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]
This one is as easy as it gets:
const arr = [1, 2, 3, 4]; console.log(arr.toReversed()); // Output 👉 [4, 3, 2, 1]
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']
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:
You can check if there have been any compatibility updates here.
🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉