Keeping data immutable in JavaScript
Copy, do not mutate — and know how deep the copy goes.
const state = {
lang: "javascript",
runs: [104, 98],
meta: { updated: "2026-07-30" },
};
const shallow = { ...state, runs: [...state.runs, 91] };
shallow.meta.updated = "changed"; // shared with state
console.log(state.meta.updated, shallow.runs);
const deep = structuredClone(state);
deep.meta.updated = "isolated";
console.log(state.meta.updated, deep.meta.updated);
const frozen = Object.freeze({ nested: { a: 1 } });
frozen.nested.a = 2; // allowed: freeze is shallow
console.log(Object.isFrozen(frozen), frozen.nested.a);
How it works
- Spread and the to* methods copy one level.
structuredClonecopies deeply, including Maps and Dates.Object.freezestops writes, but only at the top level.
Keywords and builtins used here
Objectconst
The run, in numbers
- Lines
- 17
- Characters to type
- 529
- Tokens
- 147
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 80 seconds.
Step 4 of 4 in Objects under the hood, step 15 of 16 in Functions & patterns.