Immutable Data Patterns With Spread and structuredClone
Update objects and arrays without mutating them using spread, toSorted, with and structuredClone. See shallow versus deep copies and where freezing helps.

Immutable data means that once a value is created, you never change it in place. To update something, you build a new value that shares what stayed the same. The practice removes a whole class of bugs where two parts of a program hold the same object and one of them changes it, and it makes change detection cheap, which is why React and Redux rely on it. This post covers the tools JavaScript gives you on Node.js 24: object and array spread, the non-mutating array methods, structuredClone for deep copies, Object.freeze for enforcement, and the shallow-copy trap that catches almost everyone.
The bug that mutation causes
Two parts of a program share an object, and one changes it.
const defaults = { theme: "light", sidebar: { open: true } };
function applyUserSettings(settings) {
settings.theme = "dark";
return settings;
}
const userSettings = applyUserSettings(defaults);
console.log(userSettings.theme);
console.log(defaults.theme);dark
darkThe function was meant to produce settings for one user, and it changed the shared defaults, so every later user starts dark. Nothing in the code looks wrong, since the assignment is the whole point of the function. The defect is that the function modified its input. Immutable style has a simple rule against it: functions return new values and leave their arguments alone.
Updating objects with spread
Object spread copies an object's own enumerable properties into a new one, and later properties override earlier ones.
const defaults = { theme: "light", sidebar: { open: true } };
function applyUserSettings(settings) {
return { ...settings, theme: "dark" };
}
const userSettings = applyUserSettings(defaults);
console.log(userSettings.theme, defaults.theme);
console.log(userSettings === defaults);dark light
falseThe defaults are untouched, and the result is a new object. Spread is concise for changing one property and keeping the rest. Putting the override last matters: { theme: "dark", ...settings } would let the original value win.
Updating arrays
Array methods split into two groups. push, pop, shift, unshift, splice, sort and reverse change the array in place. map, filter, slice, concat and spread return new arrays. Recent versions of JavaScript added non-mutating twins for the mutating ones: toSorted, toReversed, toSpliced and with, all available in Node.js 20 and later.
const scores = [30, 10, 20];
const sorted = scores.toSorted((a, b) => a - b);
const reversed = scores.toReversed();
const replaced = scores.with(1, 99);
const added = [...scores, 40];
const removed = scores.filter((n) => n !== 10);
console.log(sorted, reversed, replaced);
console.log(added, removed);
console.log(scores);[ 10, 20, 30 ] [ 20, 10, 30 ] [ 30, 99, 20 ]
[ 30, 10, 20, 40 ] [ 30, 20 ]
[ 30, 10, 20 ]The original array is unchanged after all five operations. with(index, value) replaces one element and returns a copy, which used to need map with an index check or a slice and spread. Before these methods, the idiom [...arr].sort() made a copy first, and you will still see it in older code.
The shallow-copy trap
Spread copies one level. Nested objects are shared between the original and the copy, so changing a nested value changes both.
const original = { theme: "light", sidebar: { open: true } };
const copy = { ...original };
copy.sidebar.open = false;
console.log(original.sidebar.open);
console.log(copy.sidebar === original.sidebar);false
trueThe sidebar object is the same object in both, so the "copy" was not independent. This is the most common immutability bug, and it looks like the code is doing the right thing. There are two fixes. Copy each level you change, or make a deep copy.
Copy the path you change
The first approach, often called structural sharing, copies only the objects along the path to the changed value and reuses everything else.
const state = {
user: { name: "Ada", prefs: { theme: "light", sidebar: { open: true } } },
items: [1, 2, 3],
};
const next = {
...state,
user: {
...state.user,
prefs: {
...state.user.prefs,
sidebar: { ...state.user.prefs.sidebar, open: false },
},
},
};
console.log(state.user.prefs.sidebar.open, next.user.prefs.sidebar.open);
console.log(next.items === state.items);
console.log(next.user.prefs.sidebar === state.user.prefs.sidebar);true false
true
falseThe unchanged items array is shared by reference, which costs nothing and is safe because neither side mutates it. The objects along the path are new. This is exactly how Redux reducers work, and it makes "did this part change?" a cheap === comparison, which is what lets React skip re-rendering unchanged branches.
Deeply nested spreads are tedious, and easy to get wrong. A small helper or a library such as Immer lets you write the change as a mutation on a draft and produces the immutable result. For a few levels, plain spread is clear enough.
Deep copies with structuredClone
structuredClone makes a full, independent copy of a value, following nested objects, arrays, maps, sets and dates. It is built into Node.js 17 and later and in current browsers.
const original = {
name: "report",
tags: ["a", "b"],
meta: { created: new Date("2026-11-20T00:00:00Z"), seen: new Set([1, 2]) },
};
const copy = structuredClone(original);
copy.tags.push("c");
copy.meta.seen.add(3);
console.log(original.tags, copy.tags);
console.log(original.meta.seen.size, copy.meta.seen.size);
console.log(copy.meta.created instanceof Date, copy.meta.created === original.meta.created);[ 'a', 'b' ] [ 'a', 'b', 'c' ]
2 3
true falseThe copy has its own arrays, its own Set and a distinct Date. Compare that with JSON.parse(JSON.stringify(x)), the old trick: it turns dates into strings, drops undefined and functions, throws on circular references and cannot represent a Set or Map. structuredClone keeps those types and handles cycles.
It has limits. It cannot clone functions, and throws a DataCloneError if you try. It does not preserve class prototypes: a class instance comes back as a plain object with the same own properties.
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
norm() {
return Math.hypot(this.x, this.y);
}
}
const copy = structuredClone(new Point(3, 4));
console.log(copy, copy instanceof Point, typeof copy.norm);
try {
structuredClone({ run() {} });
} catch (err) {
console.log(err.name);
}{ x: 3, y: 4 } false undefined
DataCloneErrorThe clone lost its prototype, so norm is gone. If you need deep copies of class instances, add a clone() method to the class.
A deep copy is also the heavier tool. It copies everything, including large parts you did not change. Prefer copying the path when you update a big state tree often, and use structuredClone when you need a fully isolated snapshot, such as saving an undo state, passing data to code you do not trust, or building a test fixture.
Enforcing immutability with freeze
Discipline is easy to lose. Object.freeze makes an object's own properties read-only. In strict mode, which modules use by default, an attempted change throws.
const config = Object.freeze({ retries: 3, nested: { debug: false } });
try {
config.retries = 5;
} catch (err) {
console.log(err.constructor.name, err.message);
}
config.nested.debug = true;
console.log(config.nested.debug, Object.isFrozen(config), Object.isFrozen(config.nested));TypeError Cannot assign to read only property 'retries' of object '#<Object>'
true true falseFreezing is shallow, just like spread: the top level is locked, and nested is still mutable. A recursive deepFreeze handles that.
function deepFreeze(value) {
if (value === null || typeof value !== "object") return value;
for (const key of Reflect.ownKeys(value)) deepFreeze(value[key]);
return Object.freeze(value);
}
const config = deepFreeze({ retries: 3, nested: { debug: false } });
try {
config.nested.debug = true;
} catch (err) {
console.log(err.message);
}Cannot assign to read only property 'debug' of object '#<Object>'Freezing in development and tests catches accidental mutation at the line that does it, which is far more useful than finding a changed value two modules later. It has a cost, so many teams freeze only in non-production builds. TypeScript offers a compile-time version: readonly properties, ReadonlyArray<T> and as const make mutation a type error with no run-time cost.
What copying costs
Copying is cheap for small values and can become expensive for large ones. Spreading an array of a hundred thousand items on every update is a hundred thousand writes, and doing it in a loop turns a linear task into a quadratic one.
// builds the array by copying it on every step
let slow = [];
for (let i = 0; i < 5; i++) slow = [...slow, i];
// builds it once
const fast = Array.from({ length: 5 }, (_, i) => i);
console.log(slow, fast);[ 0, 1, 2, 3, 4 ] [ 0, 1, 2, 3, 4 ]Both give the same result, and the first copies the growing array on each iteration. For five items it does not matter. For large inputs, build the result with map, filter or reduce in one pass, or mutate a local array that nothing else can see and return it. Mutating something you created inside the function, before anyone else has a reference, does not break immutability, since the rule is about values that other code can observe.
Testing
Test that a function returns a new value and leaves its input unchanged. Freezing the input in the test turns any mutation into a failure.
import assert from "node:assert/strict";
import { test } from "node:test";
function addTag(post, tag) {
return { ...post, tags: [...post.tags, tag] };
}
test("addTag does not change its argument", () => {
const post = Object.freeze({ id: 1, tags: Object.freeze(["js"]) });
const updated = addTag(post, "node");
assert.deepEqual(updated.tags, ["js", "node"]);
assert.deepEqual(post.tags, ["js"]);
assert.notEqual(updated, post);
});✔ addTag does not change its argument (0.8ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0If addTag called post.tags.push(tag), the frozen array would throw and the test would fail at the exact line.
When not to bother
Local variables inside one function, built up and returned, do not need immutable treatment. Performance-critical inner loops, large buffers and typed arrays are often mutated on purpose. The benefits of immutability are largest for shared state: application state, function arguments, cached values and anything that crosses a module boundary.


