QuestionsJavaScript

Immutable array copies (toSorted/toReversed/with) & structuredClone

Immutable OperationsMediumJavaScript

Which array methods mutate vs return a copy, and how do the newer change-by-copy methods plus structuredClone help state management?

What it tests

Knowing the mutating traps (sort/reverse/splice) and the modern non-mutating alternatives for React/Redux state.

Approach & answer

Several classic Array methods MUTATE in place and surprise people: sort(), reverse(), splice(), push/pop/shift/unshift, fill, copyWithin — calling `state.sort()` in React silently mutates the existing array (breaking referential-equality change detection) and returns the same reference. ES2023 added change-by-copy counterparts that leave the original untouched and return a NEW array: `toSorted()` (copy of sort), `toReversed()` (copy of reverse), `toSpliced(start, delete, ...items)` (copy of splice), and `with(index, value)` (copy with one index replaced — the immutable alternative to `arr[i] = v`). These are exactly what you want for immutable state updates: `setItems(items.toSorted(cmp))` gives a fresh array so React sees a new reference. For DEEP copies of nested objects/arrays, the spread operator and Object.assign are only SHALLOW (nested references are shared); `structuredClone(value)` (a global) makes a true deep clone, handling nested structures, Dates, Maps, Sets, typed arrays, and even cyclic references — things JSON.parse(JSON.stringify(x)) silently corrupts (drops functions/undefined, mangles Dates, throws on cycles). structuredClone can't copy functions, DOM nodes, or class prototypes (it throws / returns plain objects). Rule: use with/toSorted/toSpliced for one-level array edits, structuredClone for deep nested clones, spread for shallow.

Use this technique when

Updating React/Redux state without mutation, sorting/reordering derived data safely, and deep-cloning nested config or cached payloads.

Complexity

Copy methods are O(n); structuredClone is O(size of graph).

References

js