JavaScript Reference ยท Practical Pages
Immutability patterns: copying and freezing
Concept page on immutability in JavaScript: const versus frozen objects, shallow and deep copies, non-mutating array methods and immutable update patterns.
An immutable value is one that is never changed after it is created; to "change" it you build a new value. Strings and numbers already work this way. Objects and arrays are mutable by default, which is convenient but leads to bugs when two parts of a program hold the same object and one of them changes it unexpectedly.
Immutable patterns make data flow easier to follow: a function that returns a new object cannot surprise its caller by altering the old one, comparisons by reference (before !== after) can detect changes cheaply, and frameworks that re-render on new references rely on it.
const is not immutability
const stops you from reassigning the variable. It does not stop the object it points at from being changed.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Copy instead of mutate
Spread syntax builds new arrays and objects in one line. Each copy is shallow: nested objects are still shared with the original.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
The last line shows structural sharing: renamed reuses the original address object, and only moved has a new one. This is cheap and safe as long as nobody mutates the shared parts.
Non-mutating array methods
Many array methods change the array; newer ones return a copy instead.
| Mutates the array | Copying alternative |
|---|---|
sort() |
toSorted() or [...a].sort() |
reverse() |
toReversed() or [...a].reverse() |
splice() |
toSpliced() or slice() with spread |
a[i] = x |
with(i, x) |
push(), pop(), shift(), unshift() |
[...a, x], slice(0, -1), slice(1), [x, ...a] |
map(), filter(), slice(), concat(), flat() and flatMap() already return new arrays. toSorted(), toReversed(), toSpliced() and with() are recent additions; check a compatibility table, or use the spread-and-copy versions.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Deep copies
When you need a fully independent copy, structuredClone() copies nested objects, arrays, Map, Set and Date values. It throws for functions and cannot copy class instances' prototypes. See structuredClone().
Freezing
Object.freeze(obj) makes an object's own properties read-only and prevents adding or removing properties. It is shallow: nested objects stay mutable unless you freeze them too. In sloppy mode a write to a frozen object fails silently; in strict mode (and in modules and classes) it throws a TypeError.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Related tools: Object.seal() (no adding or removing, existing values still writable) and Object.preventExtensions() (no adding).
Usage notes
- Shallow copy, shared children. Spread,
Object.assign(),slice()andArray.from()copy one level only. - Update nested data on the path only. Copy each level between the root and the changed value, and reuse everything else.
- Freeze in development, copy in production code. Freezing helps catch accidental mutation, but it has a runtime cost for big structures.
- Immutable does not mean slow. Sharing unchanged parts keeps updates cheap; copying a large array on every keystroke is the real hazard.
- Typed arrays cannot be frozen when they have elements, and
Object.freeze()does not protect the contents of aMaporSet(theirset()andadd()still work). - Frozen is permanent. There is no unfreeze; make a copy to get a mutable version.
- Libraries. Immer and Immutable.js offer structural updates with a nicer API; they are optional.
Browser support
Spread, Object.freeze() and structuredClone() are widely supported; toSorted(), toReversed(), toSpliced() and with() are newer, so check a compatibility table for older browsers.