Objects & Prototypes
Shallow Copy vs Deep Copy
Master object cloning in JavaScript. Contrast shallow copying using Object.assign and spread syntax with deep copying using structuredClone and JSON helpers.
1. Introduction
In JavaScript, primitive values are copied by value, while objects are copied by reference. When cloning objects, you must choose between a Shallow Copy (copying top-level properties but sharing nested object references) and a Deep Copy (recursively duplicating the entire object structure).
2. Why It Matters
Modifying a nested object in a shallow copy changes the original object too, which can lead to bugs. Knowing how to create deep copies is essential for managing state immutably.
3. Real-World Analogy
Think of a House Key and Blueprint:
- Shallow Copy: Giving a friend a spare key to your house. You now have two keys, but they both open the exact same house. If your friend paints the living room wall, your living room wall changes too.
- Deep Copy: Copying the architectural blueprints and building a second, identical house in a different city. Changes made to one house have no effect on the other.
4. Shallow Copying
Shallow copies duplicate top-level values. Any nested objects are copied as references, meaning they point to the same locations in memory as the original object.
Common methods: Spread operator ({ ...obj }) and Object.assign({}, obj).
5. Deep Copying
Deep copies recursively duplicate all properties, creating completely independent nested structures in memory.
Common methods:
structuredClone(obj): The modern, native standard for deep copying.JSON.parse(JSON.stringify(obj)): A legacy serialization approach. It has limitations: it drops functions, symbols, and undefined values, and throws errors on circular references.
6. Comparison Summary
| Feature | Shallow Copy | Deep Copy |
|---|---|---|
| Nested references | Shared (pointing to same memory) | Cloned (independent memory) |
| Performance cost | Low (fast execution) | High (slow, recursive traversal) |
| Native Methods | { ...obj }, Object.assign |
structuredClone() |
7. Common Mistakes
- Using JSON.stringify on complex objects: Using the JSON utility to clone objects containing dates, maps, sets, or regex patterns leads to data loss because they are serialized to strings or empty objects.
8. Quick Quiz
Q1: Which native JavaScript method is recommended for deep copying objects in modern browsers?
A) Object.assign()
B) structuredClone()
Answer: B — structuredClone() is the native, modern method designed for deep cloning complex objects safely.
9. Scenario-Based Challenge
The Multi-Level State Mutator:
You write a state manager for a dashboard. The dashboard configuration includes nested panel settings: { title: "Logs", charts: { visible: true } }. When a user toggles a chart visibility, verify that copying the state using spread notation mutates nested visibility values across copies, and implement a safe cloning fix.
10. Debugging Exercise
Explain why this deep clone attempt throws a TypeError:
const node = { id: 1 }; node.self = node; // circular reference!
const copy = JSON.parse(JSON.stringify(node)); // crashes!
View Solution
Diagnosis: The JSON utility cannot serialize circular references, throwing a TypeError: Converting circular structure to JSON.
Fix: Use structuredClone(), which handles circular references automatically without throwing errors:
const copy = structuredClone(node); // works correctly!
11. Interview Questions
🟢 Q1: What are the differences between JSON.stringify and structuredClone for cloning objects?
Answer:
• JSON.stringify converts objects to strings, losing non-JSON values (like functions, symbols, and undefined) and throwing errors on circular references. It also converts complex types (like Date, Map, or Set) to plain strings or empty objects.
• structuredClone is a native API that handles circular references, preserves complex types (like Date, Map, Set, RegExp, and ArrayBuffer), and clones values accurately without data loss. However, it still cannot clone functions or DOM nodes.
12. Production Considerations
- • Performance Tuning: Deep cloning is a CPU-intensive operation. Avoid deep cloning large, complex objects inside high-frequency paths (like request middleware or event loop handlers). Try to design your data structures to use shallow copies instead whenever possible.