Shallow Copy vs Deep Copy in JavaScript and When It Matters
A shallow copy shares nested objects, and a deep copy duplicates every level. See which copies are shallow and where JSON cloning loses data.

Copy an object, change something inside the copy, and the original changes too. That bug is the reason this topic exists, and the explanation is the reference rule: a copy of an object copies the top level, and any object stored inside is a link to the same place. Whether the result is "shallow" or "deep" is a statement about how many of those links were followed. This post lists which operations are shallow, shows what a JSON round trip loses, demonstrates structuredClone(), and argues for a third option that most code should prefer, which is to copy only what changes. All examples run on Node.js 24. The model underneath is in the post on primitives versus objects, and the built-in deep copy has its own post.
Every common copy is shallow
The forms people reach for first copy one level.
const original = {
name: "Ada",
scores: [90, 85],
address: { city: "London" },
};
const copies = {
spread: { ...original },
assign: Object.assign({}, original),
entries: Object.fromEntries(Object.entries(original)),
};
for (const [label, copy] of Object.entries(copies)) {
console.log(label, copy.scores === original.scores, copy.address === original.address);
}
const list = [{ n: 1 }, { n: 2 }];
const arrayCopies = [list.slice(), [...list], Array.from(list), list.concat()];
console.log(arrayCopies.every((c) => c[0] === list[0] && c !== list));spread true true
assign true true
entries true true
trueEach top-level copy is a new object, and each shares scores and address with the original. The array copies are new arrays holding the same element objects. A shallow copy is perfect when the nested values are primitives, or when you replace nested values instead of editing them.
The bug appears the moment you edit through the copy.
const settings = { theme: "light", panels: { left: true } };
const draft = { ...settings };
draft.theme = "dark";
draft.panels.left = false;
console.log(settings.theme);
console.log(settings.panels.left);light
falseThe top-level theme stayed independent, and the nested panels object was shared, so the original lost its panel setting. In an application the draft is usually a form state, and the "original" is the saved record, so an unsaved edit corrupts saved data.
The JSON round trip
The old trick for a deep copy is to serialize and parse. It does copy every level, and it changes anything JSON cannot represent.
const source = {
id: 1,
created: new Date("2026-01-02T03:04:05Z"),
tags: new Set(["a", "b"]),
lookup: new Map([["k", 1]]),
missing: undefined,
nan: NaN,
big: Infinity,
fn() {
return 1;
},
nested: { ok: true },
};
const clone = JSON.parse(JSON.stringify(source));
console.log(clone);
console.log(typeof clone.created);
const circular = { name: "loop" };
circular.self = circular;
try {
JSON.stringify(circular);
} catch (error) {
console.log(error.name + ": " + error.message.split("\n")[0]);
}
try {
JSON.stringify({ id: 10n });
} catch (error) {
console.log(error.name + ": " + error.message);
}{
id: 1,
created: '2026-01-02T03:04:05.000Z',
tags: {},
lookup: {},
nan: null,
big: null,
nested: { ok: true }
}
string
TypeError: Converting circular structure to JSON
TypeError: Do not know how to serialize a BigIntThe date became a string, the set and map became empty objects, undefined and the function vanished, NaN and Infinity became null, and circular references and bigint values threw. Data that is plain numbers, strings, booleans, arrays and plain objects survives intact. That is a real subset, and the cost of the trick is that it fails quietly on everything else, so a date-bearing record loses its type without a warning. We use it only for data that came from JSON in the first place.
structuredClone
structuredClone() is the built-in deep copy, available in Node.js 17 and later and in every current browser. It follows the same algorithm used to send data between workers.
const source = {
created: new Date("2026-01-02T03:04:05Z"),
tags: new Set(["a"]),
lookup: new Map([["k", { deep: 1 }]]),
pattern: /ab+c/gi,
bytes: new Uint8Array([1, 2, 3]),
nested: { list: [1, [2, 3]] },
big: 10n,
};
source.self = source;
const clone = structuredClone(source);
console.log(clone.created instanceof Date);
console.log(clone.tags instanceof Set, clone.lookup.get("k") !== source.lookup.get("k"));
console.log(clone.nested.list[1] !== source.nested.list[1]);
console.log(clone.self === clone, clone.self === source);
console.log(clone.bytes, clone.big);
try {
structuredClone({ run() {} });
} catch (error) {
console.log(error.name + ": " + error.message);
}true
true true
true
true false
Uint8Array(3) [ 1, 2, 3 ] 10n
DataCloneError: run() {} could not be cloned.Dates, sets, maps, regular expressions, typed arrays and bigint all survived with their types, nested containers were duplicated, and the circular reference was preserved: clone.self points at the clone, not the source. The one hard failure is a function, which throws a DataCloneError. Class instances lose their prototype and come back as plain objects, which the structuredClone() post covers in detail.
The third way: copy only the path that changes
Most code that reaches for a deep copy wants to change one value and keep everything else. Cloning the whole structure to do that is wasteful and easy to avoid. An immutable update copies the objects along the path from the root to the change and reuses the rest.
const state = {
user: { name: "Ada", prefs: { theme: "light", lang: "en" } },
items: [{ id: 1, done: false }, { id: 2, done: false }],
};
const next = {
...state,
user: { ...state.user, prefs: { ...state.user.prefs, theme: "dark" } },
items: state.items.map((item) => (item.id === 2 ? { ...item, done: true } : item)),
};
console.log(next.user.prefs.theme, state.user.prefs.theme);
console.log(next.items[1].done, state.items[1].done);
console.log(next.items[0] === state.items[0]);
console.log(next.user.prefs.lang === state.user.prefs.lang);dark light
true false
true
trueThe new state has a new root, a new user, new prefs and a new second item, and everything else is shared with the old state: the first item is the identical object. That sharing is why the approach is cheap and why libraries that compare references, such as React and Redux, can detect what changed. The cost is verbosity for deeply nested data, which is what helper libraries address, and the rule that you must never mutate the shared parts afterward.
Copying at the right boundary
Copying is a defense against mutation, and the boundary where mutation can escape is where it belongs. A function that receives an array and sorts it should copy first. A module that hands out its internal list should return a copy, or a frozen view. A function that only reads its input needs no copy at all.
function sortedNames(users) {
return users.map((u) => u.name).sort();
}
function sortInPlaceBug(users) {
return users.sort((a, b) => a.name.localeCompare(b.name));
}
const users = [{ name: "Grace" }, { name: "Ada" }];
console.log(sortedNames(users));
console.log(users.map((u) => u.name));
console.log(sortInPlaceBug(users).map((u) => u.name));
console.log(users.map((u) => u.name));
console.log(users.toSorted((a, b) => b.name.localeCompare(a.name)).map((u) => u.name));
console.log(users.map((u) => u.name));[ 'Ada', 'Grace' ]
[ 'Grace', 'Ada' ]
[ 'Ada', 'Grace' ]
[ 'Ada', 'Grace' ]
[ 'Grace', 'Ada' ]
[ 'Ada', 'Grace' ]sortedNames builds a new array with map first, so the input is untouched. sortInPlaceBug sorted the caller's array, and the caller saw the order change. toSorted(), available from Node.js 20, is the non-mutating version of sort() and avoids the issue without a manual copy. Prefer the non-mutating methods, toSorted, toReversed, toSpliced and with, over copy-then-mutate.
Detecting a shared reference in a test
A test can pin the intent of a copy by asserting identity on the parts that must differ and on the parts that may be shared. That documents which kind of copy the function makes and catches a refactor that swaps one for the other.
import { test } from "node:test";
import assert from "node:assert/strict";
const withTheme = (state, theme) => ({
...state,
prefs: { ...state.prefs, theme },
});
test("a path update leaves the original alone", () => {
const state = { prefs: { theme: "light" }, items: [1] };
const next = withTheme(state, "dark");
assert.equal(state.prefs.theme, "light");
assert.notEqual(next.prefs, state.prefs);
assert.equal(next.items, state.items);
});Run it with node --test on Node.js 24. The last assertion says the unchanged items array is shared on purpose, and it fails if someone replaces the update with a full deep clone, which would be correct but would break reference-based change detection downstream. Tests that check identity are unusual and worth having for any function that claims to be an immutable update.
How to choose
If the data is plain and shallow, spread. If you change one nested value, update the path. If you need a full independent copy of data that may contain dates, maps, sets or cycles, structuredClone(). If the data came from JSON and you are certain it is plain, a JSON round trip works and structuredClone() is still safer. If it contains class instances or functions, write a clone method on the class, since no generic tool knows how to rebuild them.
| Situation | Tool |
|---|---|
| Flat object or array of primitives | Spread or slice() |
| Change one nested value | Immutable path update |
| Full independent copy of plain data with dates, maps or cycles | structuredClone() |
| Class instances with methods | A clone() method you write |
| Data you will never mutate | No copy at all |
Copying class instances
Class instances are the case no built-in handles well. structuredClone() returns a plain object without the prototype, so methods vanish, and spread copies own properties into a plain object too. If your model objects have behavior, give them a method that rebuilds one, and call it where you need a copy.
class Cart {
constructor(items = []) {
this.items = items;
}
total() {
return this.items.reduce((sum, item) => sum + item.price, 0);
}
clone() {
return new Cart(this.items.map((item) => ({ ...item })));
}
}
const cart = new Cart([{ price: 5 }, { price: 7 }]);
const viaClone = structuredClone(cart);
const viaMethod = cart.clone();
console.log(typeof viaClone.total, viaClone instanceof Cart);
console.log(viaMethod.total(), viaMethod instanceof Cart);
console.log(viaMethod.items[0] === cart.items[0]);undefined false
12 true
falseThe structured clone kept the data and dropped the behavior, so total is not a function on it. The hand-written clone() returns a real Cart with its own item objects. Writing the method puts the knowledge of how to copy next to the knowledge of what the class holds, which is the only place it can be correct.
Where this advice stops
If the data is huge, a deep copy costs time and memory in proportion to its size, and structural sharing or a persistent data structure library is a better fit. If you are copying only to make comparisons, such as detecting changes in a form, compare field by field and avoid the copy. And if a copy is made out of caution on every call, remove it: unnecessary copies are a measurable cost in hot paths, and they hide the real question of who is allowed to mutate what.
The structured clone algorithm is described in the HTML Standard under safe passing of structured data, and MDN's page on structuredClone lists what it supports.


