Hiprup

What are toSorted, toReversed, and toSpliced (ES2023)?

ES2023 added immutable versions of the mutating array methods — they return a new array and leave the original unchanged.

  • toSorted() — like sort() but returns a sorted copy.

  • toReversed() — like reverse() but returns a reversed copy.

  • toSpliced() — like splice() but returns a modified copy.

  • with(i, val) — returns a copy with one index changed.

Great for immutable patterns like React state — no more copying before sorting.

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

// Old (mutating)
const sorted = arr.sort();     // arr is NOW modified!
console.log(arr);               // [1, 1, 3, 4, 5] — mutated!

// New (non-mutating)
const arr2 = [3, 1, 4, 1, 5];
const sorted2 = arr2.toSorted();
console.log(arr2);               // [3, 1, 4, 1, 5] — unchanged!
console.log(sorted2);            // [1, 1, 3, 4, 5] — new array

// toReversed
const reversed = [1, 2, 3].toReversed(); // [3, 2, 1]

// toSpliced
const spliced = [1, 2, 3, 4, 5].toSpliced(1, 2, 'a', 'b');
// [1, 'a', 'b', 4, 5] — original unchanged

// with (replace at index)
const updated = [1, 2, 3].with(1, 'x'); // [1, 'x', 3]

// Before ES2023, you had to copy first:
const safeSorted = [...arr].sort(); // Copy then sort

toSorted returns a new sorted array — the original is untouched. Same for toReversed and toSpliced. with(index, value) replaces a single element immutably.

Before ES2023, the workaround was [...arr].sort() to copy first. These methods align JS with functional programming principles (no mutation).

These solve the mutation problem: sort/reverse/splice modify the original array (surprise!). The ES2023 versions return new arrays.

Before: [...arr].sort() workaround. Now: arr.toSorted() directly. with() for immutable element replacement is a bonus.

What are toSorted, toReversed, and toSpliced (ES2023)? | Hiprup