Why does changing a copy change the original?
const original = {
name: "Alex",
preferences: { theme: "light" },
};
const alias = original;
const copy = { ...original };
copy.preferences.theme = "dark";
copy.name = "Sam";
console.log(alias === original); // true
console.log(copy === original); // false
console.log(copy.preferences === original.preferences); // true
console.log(original.preferences.theme); // "dark"
console.log(original.name); // "Alex"
Assignment with alias = original retains object identity. Spread creates a new top-level object, but object-valued properties still refer to the same objects. [1][2]
Changing name in this example affects only the copy, whereas changing preferences.theme affects both. Use === to inspect shared identity, not to compare contents.
Spread, Object.assign() and array copies
const defaults = {
pageSize: 20,
filters: { active: true },
};
const overrides = { pageSize: 50 };
const settings = { ...defaults, ...overrides };
const assigned = Object.assign({}, defaults, overrides);
console.log(settings.pageSize); // 50
console.log(assigned.filters === defaults.filters); // true
const rows = [{ id: 1, selected: false }];
const copiedRows = rows.slice();
copiedRows[0].selected = true;
console.log(rows[0].selected); // true
Spread and Object.assign({}, source) copy own enumerable properties, including symbol keys. They do not preserve source descriptors or the prototype; reading properties may invoke getters. Object.assign(target, source) mutates the target and can invoke its setters. [2][3]
Both work well for merging flat configuration. Array slice() and array spread are also shallow: the new array still contains the original element objects. [1]
When should you use structuredClone()?
const shared = { count: 1 };
const original = {
createdAt: new Date("2025-01-01T00:00:00Z"),
labels: new Set(["draft"]),
items: new Map([["first", shared]]),
selected: shared,
};
original.self = original;
const copy = structuredClone(original);
copy.selected.count = 2;
console.log(copy.createdAt instanceof Date); // true
console.log(copy.labels instanceof Set); // true
console.log(copy.items instanceof Map); // true
console.log(copy.self === copy); // true
console.log(copy.items.get("first") === copy.selected); // true
console.log(original.selected.count); // 1
structuredClone() duplicates a supported data graph, preserving cycles and internal shared references. Supported types include Date, Map, Set and typed arrays. [4][5]
The map entry and selected still point to one object in the clone, but changing its count leaves the source intact. This is useful for independent drafts and data snapshots.
Why does structuredClone not copy everything?
class Product {
constructor(price) {
this.price = price;
}
getTotal(quantity) {
return this.price * quantity;
}
}
const original = new Product(25);
const copy = structuredClone(original);
console.log(copy.price); // 25
console.log(copy instanceof Product); // false
console.log(typeof copy.getTotal); // "undefined"
const restored = new Product(copy.price);
console.log(restored.getTotal(2)); // 50
try {
structuredClone({ calculate: () => 25 });
} catch (error) {
if (error.name !== "DataCloneError") {
throw error;
}
console.log(error.name); // "DataCloneError"
}
Functions and DOM nodes cannot be cloned by this algorithm. Custom class prototypes, property descriptors and private class fields are not reproduced. Attempting to clone a function raises DataCloneError. [5]
For a domain entity, reconstruct an instance explicitly from its data through a constructor or factory. Do not assume cloning will retain methods or invariants.
Why does JSON.parse(JSON.stringify()) change data?
const original = {
date: new Date("2025-01-01T00:00:00Z"),
missing: undefined,
score: Infinity,
labels: new Set(["draft"]),
values: [undefined, NaN],
};
const copy = JSON.parse(JSON.stringify(original));
console.log(typeof copy.date); // "string"
console.log(Object.hasOwn(copy, "missing")); // false
console.log(copy.score); // null
console.log(copy.labels); // {}
console.log(copy.values); // [null, null]
JSON serializes data to text. Date normally becomes a string, object properties containing undefined disappear, and NaN and Infinity become null. Map and Set normally become empty objects without custom serialization. [6]
BigInt without custom conversion and circular references cause errors. JSON is appropriate for data deliberately constrained to an interchange format, not for arbitrary JavaScript object cloning.
How to update nested state without copying everything
const state = {
profile: {
name: "Alex",
address: { city: "Gdansk", country: "PL" },
},
preferences: { theme: "dark" },
};
function updateCity(state, city) {
if (state.profile.address.city === city) {
return state;
}
return {
...state,
profile: {
...state.profile,
address: {
...state.profile.address,
city,
},
},
};
}
const next = updateCity(state, "Krakow");
console.log(state.profile.address.city); // "Gdansk"
console.log(next.profile.address.city); // "Krakow"
console.log(next.preferences === state.preferences); // true
console.log(updateCity(state, "Gdansk") === state); // true
In React state, copy the objects along the path from the changed field to the root while retaining unchanged branches. The example can be called with setState(previous => updateCity(previous, city)). [7]
Retaining identity on unchanged branches supports identity comparisons and memoization. The function returns the old state when there is no change. This requires treating shared branches as immutable; it is not a fully independent copy.
Copying large data and transferring ArrayBuffer
const bytes = new Uint8Array([10, 20, 30]);
const cloned = structuredClone(bytes);
cloned[0] = 99;
console.log(bytes[0]); // 10
const moved = structuredClone(bytes, {
transfer: [bytes.buffer],
});
console.log(bytes.byteLength); // 0
console.log(moved[0]); // 10
console.log(moved.byteLength); // 3
A full copy requires visiting data and allocating additional memory; there is no universally fastest method. Measure time and allocation with representative structures.
Transferring an ArrayBuffer moves the resource instead of duplicating its contents and detaches the source buffer. Do this only when the source is no longer needed. Cloning a SharedArrayBuffer does not create independent backing memory either. [4][8]
