The Shallow Copy Trap
What you'll learn: Why spreading or using Object.assign doesn't fully protect nested data from mutation.
The Problem with Shallow Copies
When you copy an array or object using spread (...) or Object.assign, JavaScript only copies the top level. Any nested objects or arrays inside are not duplicated—instead, the copy gets references to the same nested structures.
This means mutating a nested property in the "copy" also mutates the original.
How It Happens
const original = {
name: "Alice",
scores: [10, 20, 30]
};
const copy = { ...original };
copy.name = "Bob"; // Safe: top-level property copied
copy.scores.push(40); // Danger: mutates original.scores too!
console.log(original.scores); // [10, 20, 30, 40] — original changed!
Even though you "copied" the object, copy.scores and original.scores point to the same array in memory.
The Analogy
Imagine photocopying a document that contains a sticky note with an address. The photocopy shows the sticky note, but both documents reference the same physical sticky note. Writing on it affects what both documents display.
How to Avoid It
For nested structures, you need deep copies:
- Manually copy each level
- Use a library like Lodash's
cloneDeep - Use
structuredClone()(modern browsers/Node)
Example with manual copying:
const safeCopy = {
...original,
scores: [...original.scores] // explicitly copy the nested array
};
Key Takeaway: Shallow copies only duplicate the first level—nested objects and arrays remain shared references, so mutating them affects the original.