Copying objects in JavaScript looks simple, but many invisible production bugs originate from copying the wrong way. Primitive values (numbers, strings, booleans) copy by value. Objects and arrays, however, are copied by reference.
Understanding the distinction between shallow copying and deep copying is critical for predictable state management, UI rendering, and preventing unintended mutations.
1. Shallow Copy & The Spread Pitfall
A shallow copy duplicates top-level properties. If a property is a primitive, it gets a new value. But if a property is an object or array, only its memory address is copied.
Common shallow copy methods:
- Object Spread:
const copy = { ...user }; - Object Assign:
const copy = Object.assign({}, user); - Array Slice / Spread:
const copyArr = [...arr];
const user = {
name: "Ali",
settings: {
theme: "dark"
}
};
// Shallow copy with spread operator
const copy = { ...user };
// Mutating a nested property on the copy
copy.settings.theme = "light";
console.log(user.settings.theme); // ❌ Output: "light" (Accidentally mutated!)
console.log(user.settings === copy.settings); // true (Same reference in memory!)2. The JSON Serialization Trick & Its Critical Limits
A widely known shortcut for deep copying is JSON.parse(JSON.stringify(obj)).
While convenient for simple data objects, it fails in production when data types go beyond basic JSON:
const complexData = {
createdAt: new Date(),
greet: () => "Hello",
score: undefined,
tags: new Set(["js", "ts"]),
price: NaN
};
// The JSON stringify/parse serialization trick
const jsonCopy = JSON.parse(JSON.stringify(complexData));
console.log(jsonCopy.createdAt); // "2026-10-08T..." (Date converted to string!)
console.log(jsonCopy.greet); // undefined (Functions dropped!)
console.log(jsonCopy.score); // undefined (undefined keys dropped!)
console.log(jsonCopy.tags); // {} (Set converted to empty object!)
console.log(jsonCopy.price); // null (NaN converted to null!)3. Proper Deep Copy: structuredClone()
Modern JavaScript now includes structuredClone(), a native global function built into all modern browsers and Node.js (v17+).
Why structuredClone() is the Modern Standard:
- Clones all nested levels recursively.
- Correctly preserves
Date,Set,Map,RegExp, andArrayBufferinstances. - Safely handles circular references without throwing errors.
const user = {
name: "Ali",
joined: new Date(),
tags: new Set(["admin", "editor"]),
settings: {
theme: "dark"
}
};
// Modern, native deep clone
const deep = structuredClone(user);
deep.settings.theme = "light";
deep.tags.add("author");
console.log(user.settings.theme); // "dark" (Safe! Not mutated)
console.log(user.tags.size); // 2 (Independent Set)
console.log(deep.joined instanceof Date); // true (Preserves Date instance)Strategy | Syntax | Copies Nested Levels? | Preserves Dates & Sets? | Circular References? | Performance |
|---|---|---|---|---|---|
Reference Assignment | b = a | No (Same object pointer) | N/A | Yes | Instant (Zero allocation) |
Shallow Copy | { ...obj } / Object.assign() | No (Level 1 only) | Preserves references | Yes | Extremely fast |
JSON Serialization | JSON.parse(JSON.stringify()) | Yes (All levels) | No (Lossy data conversion) | No (Crashes with TypeError) | Slow (String parsing) |
structuredClone() | structuredClone(obj) | Yes (All levels) | Yes (Native preservation) | Yes (Handles cycles) | Fast native engine clone |
Think it throughInterview Question: How does React / Redux perform immutable state updates safely using shallow copying?
Instead of an expensive full deep clone on every user interaction, React and Redux state reducers use nested shallow spreads on only the branches that change:
// Update user.settings.theme immutably:
const nextState = {
...state,
user: {
...state.user,
settings: {
...state.user.settings,
theme: 'light'
}
}
};
Why this matters for performance:
Unchanged branches retain identical memory references (prev.posts === next.posts), allowing React components wrapped in React.memo to skip unnecessary re-renders via fast reference equality checks.