Deep Copy vs Shallow Copy
Deep Copy vs Shallow Copy in Modern JavaScript
In JavaScript, primitive values (numbers, strings, booleans, symbols, null, undefined) are copied by value, whereas objects (including arrays, functions, and plain objects) are referenced by memory address. Misunderstanding the boundary between shallow copies and deep copies is one of the most frequent causes of state mutation bugs.
1. References vs. Copies
2. Shallow Copy: Methods and Limitations
A shallow copy creates a new outer object or array, but any nested objects or arrays inside it are still shared references.
Methods for Shallow Copying
- 1Object Spread Operator:
{ ...source } - 2Array Spread Operator:
[ ...sourceArray ] - 3Object.assign():
Object.assign({}, source) - 4Array.prototype.slice():
sourceArray.slice()
3. Deep Copying: Modern structuredClone()
A deep copy recursively duplicates every level of nested objects and arrays, ensuring complete isolation in memory.
The Modern Standard: structuredClone()
Introduced natively in modern JavaScript (Node.js 17+ and all modern browsers):
Features of structuredClone():
- Handles nested objects and arrays to any depth.
- Supports cyclic references (objects referencing themselves).
- Preserves
Date,RegExp,Map,Set, andArrayBufferinstances. - Limitation: Does not clone functions or DOM nodes (throws
DataCloneError).
4. The Legacy JSON Hack (and its gotchas)
Critical Pitfalls of JSON.parse(JSON.stringify()):
- Discards functions and methods.
- Converts
Dateobjects into ISO strings. - Converts
NaNandInfinitytonull. - Throws errors on circular references.
- Strips
undefinedvalues andSymbolkeys.
5. Summary Cheat Sheet
| Technique | Copy Depth | Preserves Dates/RegExp? | Handles Circular Refs? | Clones Functions? |
|---|---|---|---|---|
Object.assign({}, obj) | Shallow | Yes (references) | N/A | Copies reference |
{ ...obj } | Shallow | Yes (references) | N/A | Copies reference |
JSON.parse(JSON.stringify()) | Deep | No (converts to string) | Throws Error | Drops functions |
structuredClone(obj) | Deep | Yes | Yes | Throws Error |
Practice Quiz
Object.keys, Object.values, Object.entries
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Array.from & Array.of | Object.keys, Object.values, Object.entries |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.