ECMAScript 2024 introduced three new functional manipulation methods to the Array
, TypedArray
, and String
prototypes - toSorted()
, toReversed()
, and with()
. These provide ways to manipulate array/string contents without mutating them.
toSorted()
The toSorted()
method returns a new sorted copy of the array/string it is called on. This avoids mutating the original array.
// Sort an array without mutation
const array = [5, 3, 1, 4, 2];
const sorted = array.toSorted((a, b) => a - b);
console.log(array); // [5, 3, 1, 4, 2]
console.log(sorted); // [1, 2, 3, 4, 5]
The optional sorting callback function follows the same rules as Array's sort()
.
toReversed()
Similarly, toReversed()
returns a new reversed copy of the array/string:
// Reverse a string without mutation
const str = "hello";
const reversed = str.toReversed();
console.log(str); // "hello"
console.log(reversed); // "olleh"
with()
The with()
method returns a new array/string with its elements transformed by a mapping function.
// Map over numbers and increment
const numbers = [1, 2, 3];
const incremented = numbers.with(num => num + 1);
console.log(numbers); // [1, 2, 3]
console.log(incremented); // [2, 3, 4]
This provides a cleaner way to transform contents without mutating the original.