Shallow Copy vs Deep Copy in JavaScript Objects
Understand the difference between shallow and deep copy in JavaScript objects. Learn when each matters, see mutation bugs in action, and pick the right method.
When you copy a JavaScript object, the depth of that copy determines whether nested data stays connected to the original or becomes fully independent. This single distinction is responsible for an entire category of bugs where modifying a "copy" accidentally changes the original data. Understanding shallow versus deep copy is not just theoretical; it affects how you write state management, API handlers, and any code that transforms data.
How JavaScript Stores Objects
Before comparing copy types, you need to understand how JavaScript handles reference types. Primitive values (numbers, strings, booleans) are stored directly in the variable. Objects are stored in heap memory, and the variable holds a pointer (reference) to that memory location:
// Primitives: independent copies
let a = 42;
let b = a;
b = 100;
console.log(a); // 42 (unchanged)
// Objects: shared references
let objA = { name: "Alice" };
let objB = objA;
objB.name = "Bob";
console.log(objA.name); // "Bob" (both point to same object!)Neither objA nor objB "owns" the object. They both reference the same data in memory. Any change through one variable is visible through the other. This is why cloning matters.
What Is a Shallow Copy?
A shallow copy creates a new object and copies all top-level properties from the source. However, if any property's value is an object (including arrays), the copy gets a reference to the same nested object, not an independent duplicate:
const original = {
name: "Alice",
age: 30,
address: {
city: "Portland",
state: "OR"
},
hobbies: ["reading", "hiking"]
};
// Shallow copy using spread
const shallow = { ...original };
// Top-level properties are independent
shallow.name = "Bob";
console.log(original.name); // "Alice" (safe)
// Nested objects are SHARED
shallow.address.city = "Seattle";
console.log(original.address.city); // "Seattle" (mutated!)
shallow.hobbies.push("coding");
console.log(original.hobbies); // ["reading", "hiking", "coding"] (mutated!)Here is the memory model:
| Property | original | shallow | Independent? |
|---|---|---|---|
name | "Alice" | "Bob" | Yes (primitive) |
age | 30 | 30 | Yes (primitive) |
address | {city: "Seattle"} | Same object | No (shared reference) |
hobbies | ["reading","hiking","coding"] | Same array | No (shared reference) |
What Is a Deep Copy?
A deep copy creates an entirely new object and recursively copies every nested object and array. The result is completely independent of the original:
const original = {
name: "Alice",
age: 30,
address: {
city: "Portland",
state: "OR"
},
hobbies: ["reading", "hiking"]
};
// Deep copy using structuredClone
const deep = structuredClone(original);
// Top-level properties are independent
deep.name = "Bob";
console.log(original.name); // "Alice" (safe)
// Nested objects are ALSO independent
deep.address.city = "Seattle";
console.log(original.address.city); // "Portland" (safe!)
deep.hobbies.push("coding");
console.log(original.hobbies); // ["reading", "hiking"] (safe!)Every level of nesting is duplicated. The deep copy shares nothing with the original.
Visual Comparison
SHALLOW COPY:
original ──> { name: "Alice", address: ─────> { city: "Portland" }
shallow ──> { name: "Bob", address: ──┘ }
DEEP COPY:
original ──> { name: "Alice", address: ──> { city: "Portland" } }
deep ──> { name: "Bob", address: ──> { city: "Seattle" } }
With a shallow copy, both objects share the nested address reference. With a deep copy, each has its own independent address object.
Shallow Copy Methods
JavaScript provides several ways to create shallow copies:
const original = { a: 1, b: { c: 2 } };
// Method 1: Spread operator
const copy1 = { ...original };
// Method 2: Object.assign
const copy2 = Object.assign({}, original);
// Method 3: Object.fromEntries + Object.entries
const copy3 = Object.fromEntries(Object.entries(original));All three produce the same result: top-level properties are copied by value, but nested objects share the same reference.
For arrays, the shallow copy methods are:
const arr = [1, { x: 2 }, [3, 4]];
const copy1 = [...arr];
const copy2 = arr.slice();
const copy3 = Array.from(arr);
// All produce shallow copies
copy1[1].x = 99;
console.log(arr[1].x); // 99 (nested object shared)Deep Copy Methods
const original = { a: 1, b: { c: 2, d: [3, 4] } };
// Method 1: structuredClone (recommended)
const copy1 = structuredClone(original);
// Method 2: JSON round-trip (limited, legacy)
const copy2 = JSON.parse(JSON.stringify(original));
// Method 3: Manual recursive clone
function deepClone(obj) {
if (obj === null || typeof obj !== "object") return obj;
if (Array.isArray(obj)) return obj.map(item => deepClone(item));
const clone = {};
for (const [key, value] of Object.entries(obj)) {
clone[key] = deepClone(value);
}
return clone;
}
const copy3 = deepClone(original);Deep Copy Method Comparison
| Method | Handles Dates | Handles Map/Set | Handles Functions | Circular Refs | Speed |
|---|---|---|---|---|---|
structuredClone() | Yes | Yes | No (throws) | Yes | Medium |
JSON.parse(JSON.stringify()) | No (to string) | No (to {}) | No (removed) | No (throws) | Slow |
| Manual recursive clone | Yes (with code) | Yes (with code) | Yes (with code) | No (unless tracked) | Varies |
When Shallow Copy Is Enough
Shallow copies work perfectly for flat objects with only primitive values:
// Safe with shallow copy - all primitives
const settings = {
theme: "dark",
fontSize: 16,
autoSave: true,
volume: 0.8
};
const copy = { ...settings };
copy.theme = "light";
console.log(settings.theme); // "dark" (safe)Shallow copies also work when you replace (not mutate) nested objects:
const state = {
user: { name: "Alice" },
count: 0
};
// Replacing the entire nested object is safe with shallow copy
const newState = {
...state,
user: { ...state.user, name: "Bob" } // New object, not mutation
};
console.log(state.user.name); // "Alice" (safe)This "spread at each level" pattern is exactly what React and Redux use for immutable state updates.
When You Need Deep Copy
Deep copies are necessary when:
- You mutate nested data after copying
- You pass objects to functions that might modify nested properties
- You cache or snapshot complex state for undo/redo
- You receive data from an API and need multiple independent transformations
// Undo/redo history needs deep copies
const history = [];
function saveSnapshot(state) {
history.push(structuredClone(state));
}
function undo() {
if (history.length === 0) return null;
return history.pop();
}
const appState = {
canvas: {
shapes: [
{ type: "circle", x: 10, y: 20, radius: 5 },
{ type: "rect", x: 30, y: 40, width: 10, height: 15 }
]
}
};
saveSnapshot(appState); // Save state
appState.canvas.shapes[0].x = 100; // Move circle
saveSnapshot(appState); // Save new state
const previousState = undo(); // Restore
console.log(previousState.canvas.shapes[0].x); // 100Real-World Example: API Data Transformer
Here is a practical example where shallow vs deep copy matters when processing API responses:
function processOrderData(apiResponse) {
// Deep clone because we'll modify nested arrays
const orders = structuredClone(apiResponse.data.orders);
return orders.map(order => {
// Calculate totals by modifying the cloned data
order.items.forEach(item => {
item.total = item.price * item.quantity;
item.taxAmount = item.total * 0.08;
item.finalPrice = item.total + item.taxAmount;
});
order.subtotal = order.items.reduce((sum, item) => sum + item.total, 0);
order.tax = order.items.reduce((sum, item) => sum + item.taxAmount, 0);
order.grandTotal = order.subtotal + order.tax;
return order;
});
}
const rawResponse = {
data: {
orders: [
{
id: "ORD-001",
items: [
{ name: "Laptop", price: 999, quantity: 1 },
{ name: "Mouse", price: 29, quantity: 2 }
]
}
]
}
};
const processed = processOrderData(rawResponse);
// Original API data is untouched
console.log(rawResponse.data.orders[0].items[0].total); // undefined (safe!)
console.log(processed[0].grandTotal); // 1143.72Without the deep clone, calling processOrderData would permanently modify the original API response, which could corrupt cached data or break other parts of your application.
Performance Considerations
| Operation | Relative Speed | Memory Impact |
|---|---|---|
Reference assignment (=) | Instant | None (no copy) |
| Shallow copy (spread) | Very fast | Minimal (one level) |
| Deep copy (structuredClone) | 5-20x slower than shallow | Full duplication |
| Deep copy (JSON round-trip) | 10-50x slower than shallow | String + object allocation |
For most applications, the speed difference is negligible. A deep clone of a typical API response takes microseconds. Only optimize if profiling shows cloning as a bottleneck in a hot path (like inside a loop processing thousands of objects).
Common Mistakes to Avoid
Assuming Spread Creates Deep Copies
const data = { config: { debug: true } };
const copy = { ...data };
copy.config.debug = false;
console.log(data.config.debug); // false - BUG!Using JSON Round-Trip Without Checking Types
const data = {
date: new Date(),
count: undefined,
valid: NaN
};
const clone = JSON.parse(JSON.stringify(data));
console.log(typeof clone.date); // "string" (not Date)
console.log("count" in clone); // false (undefined removed)
console.log(clone.valid); // null (NaN became null)Forgetting That Arrays Are Objects Too
const original = { tags: ["js", "web"] };
const shallow = { ...original };
shallow.tags.push("react");
console.log(original.tags); // ["js", "web", "react"] - BUG!
// Arrays inside objects need deep clone too
const safe = structuredClone(original);
safe.tags.push("react");
console.log(original.tags); // ["js", "web"] - safeDecision Flowchart
- Is the object flat (no nested objects or arrays)? Use spread
{ ...obj } - Do you need all nested data independent? Use
structuredClone() - Are you doing immutable state updates (replacing, not mutating nested data)? Spread at each level is fine
- Does the data contain functions? Use spread (shallow) or build a custom cloner
- Working with JSON-safe data in an older environment?
JSON.parse(JSON.stringify())works
Best Practices
- Default to spread for flat objects. It is the fastest and most readable shallow copy method.
- Use
structuredClone()for nested data. It is the standard deep clone with the best type support. - Prefer immutable update patterns over deep cloning. Spreading at each level (
{ ...state, user: { ...state.user, name: "new" } }) is more efficient than deep cloning the entire state tree. - Clone at boundaries, not everywhere. Clone when data crosses ownership boundaries (API responses, function inputs you do not control) rather than copying every object defensively.
- Test mutations explicitly. When writing functions that transform data, verify that the original input is unchanged after the function returns.
Rune AI
Key Insights
- Shallow copy shares nested references: modifying a nested property in the copy also modifies the original, causing hard-to-find bugs
- Deep copy creates full independence:
structuredClone()is the modern standard that handles Date, Map, Set, and circular references - Spread at each level is an alternative: for state management, spreading only the changed levels is more efficient than deep cloning everything
- JSON round-trip is a legacy approach: it destroys Date, Map, Set, undefined, NaN, and functions, so use
structuredCloneinstead - Clone at boundaries, not everywhere: clone data when it crosses ownership boundaries (API calls, shared state) rather than defensively copying every object
Frequently Asked Questions
Is structuredClone always better than JSON.parse(JSON.stringify)?
Does the spread operator deep copy arrays inside objects?
How does React handle shallow vs deep copy in state?
Can I use lodash cloneDeep instead of structuredClone?
How do I clone an object with getters and setters?
Conclusion
The difference between shallow and deep copy in JavaScript determines whether nested data stays connected to the original or becomes fully independent. Shallow copies (spread, Object.assign) duplicate top-level properties but share nested objects. Deep copies (structuredClone) recursively duplicate everything. Choosing correctly prevents the mutation bugs that are among the hardest to diagnose in JavaScript applications.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.