Historically, array methods like sort(), splice(), and reverse() change the array in place (they are destructive/mutating). If you wanted to avoid that, you had to manually copy the array first (const newArr = [...oldArr].sort()).
ES2023 fixes this with new counterparts that return a new array without touching the original:
1. toSorted()
The non-mutating version of sort().
const animals = ['unicorn', 'purple worm', 'dragon'];
// Old (Destructive):
animals.sort(); // Modifies 'animals'
// New (Non-Destructive):
const sortedAnimals = animals.toSorted();
// sortedAnimals: ['dragon', 'purple worm', 'unicorn']
// animals: ['unicorn', 'purple worm', 'dragon'] <-- Original array remains unchanged!
2. toReversed()
The non-mutating version of reverse().
const primes = [2, 3, 5, 7];
const reversedPrimes = primes.toReversed();
// reversedPrimes: [7, 5, 3, 2]
3. toSpliced(start, deleteCount, ...items)
The non-mutating version of splice(). This is arguably the most useful, as splice was the most complex to replicate manually.
const devs = ['Sergio', 'Ivan', 'Misha', 'Marc'];
// Removes Ivan and adds Carlos
const updatedDevs = users.toSpliced(2, 2, 'Carlos');
// updatedDevs: ['Sergio', 'Ivan', 'Carlos']
// devs: ['Sergio', 'Ivan', 'Misha', 'Marc']
4. with(index, value)
This method is the non-mutating way to replace an element at a specific index. It’s similar to array[index] = value but returns a new array.
Maybe in english sounds ok, but if you translate the name to spanish it’s really strange.
const colors = ['red', 'green', 'blue'];
// Replace 'green' (index 1) with 'yellow'
const newColors = colors.with(1, 'yellow');
// newColors: ['red', 'yellow', 'blue']
// colors: ['red', 'green', 'blue']
Extra update: Searching Arrays from the End
The Array.prototype gained methods to search from the end: findLast() and findLastIndex(). While simple, these eliminate the need to manually reverse an array and search, only to reverse the index back later.
const users = [
{ id: 1, name: 'A' },
{ id: 2, name: 'B' },
{ id: 1, name: 'C' } // Duplicate ID
];
// Easily find the LAST user with id: 1
const lastMatch = users.findLast(u => u.id === 1);
// lastMatch: { id: 1, name: 'C' }
And that’s all folks! See you on the next post 🙂
