typestar

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

  1. Spread and the to* methods copy one level.
  2. structuredClone copies deeply, including Maps and Dates.
  3. Object.freeze stops writes, but only at the top level.

Keywords and builtins used here

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.

Type this snippet

Step 4 of 4 in Objects under the hood, step 15 of 16 in Functions & patterns.

← Previous Next →