An immutable update builds a new version and leaves the old one untouched. The rule is path copying: copy each object between the root and the thing you change, and point the copies at the original, unchanged siblings.
The tools, and what each one actually does:
- Object spread /
Object.assign.{ ...obj }runsCopyDataProperties: own enumerable string and symbol keys, read withGet(getters run, results become plain values). One level only; nested objects are shared. - Array copying methods.
with(i, v),toSorted,toSplicedandtoReversedcame in ES2023 (Change Array by Copy). They return a new array of the same length, built withArrayCreate, so a subclass gets back a plainArray.sort,spliceandreversestill mutate. structuredClone. A deep copy defined by the HTML Standard, not ECMAScript (browsers and Node.js provide it). It copies everything and keeps nothing shared, so it is a snapshot tool, not an update tool.Object.freeze. A guard, not a copy. It's shallow: nested objects stay writable unless you freeze them too.
The cost. Each update allocates one new node per level of the path, and each new node copies all of its own keys or elements. Changing one item in a 10,000-element array copies 10,000 slots; changing one key in a deep object copies only the objects on its path. What you get back is identity: unchanged subtrees are still the same objects, so React, Redux selectors or memo can skip them with a single ===.
When arrays get large or updates frequent, that O(n) per level is what persistent data structures fix by sharing inside each node, too.