Deep Copy
A deep copy duplicates an object along with all the nested objects it contains, creating a fully independent clone, whereas a shallow copy only copies the top level and still shares references to nested values.
Learn Python, JavaScript, Java and more with free interactive lessons, real projects and AI-powered help. Beginner-friendly.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
💡 Running Code Locally: While this online editor runs real JavaScript, some advanced examples may have limitations. For the best experience:
Master memory management, reference handling, and data structure copying
Understanding how JavaScript handles data structures, memory, and copying is one of the most important skills for writing bug-free, scalable code. Many of the hardest-to-diagnose bugs come directly from not knowing whether you created a real copy or a shared reference.
JavaScript stores values in two completely different ways: by value and by reference . Primitives such as numbers, strings, booleans, null, undefined, symbol, and bigint are stored by value, meaning each assignment creates a brand-new, independent copy. Objects, arrays, functions, Maps, Sets, and Dates are stored by reference, meaning multiple variables can point to the same memory.
💡 Key Insight: Understanding this distinction lets you debug faster, structure data correctly, and build cleaner architecture.
A shallow copy duplicates only the top level of an object. It does not clone nested structures. JavaScript provides several shallow-cloning techniques that developers often assume are deep copies, which leads to subtle bugs.
⚠️ Warning: These operations are fast and convenient, but unsafe when dealing with nested structures.
A deep copy creates a fully independent clone, duplicating every level of nesting so changes never leak back into the original structure.
Many developers use JSON cloning, but it's risky because it destroys important data:
❌ Avoid: JSON cloning destroys Dates, Functions, Infinity/NaN, Undefined, and Circular references.
If you want full control, building a recursive deep clone function is the most reliable approach for understanding how cloning actually works under the hood.
Consider this common real-world situation: You fetch user data from an API and want to modify a piece of it for display without altering the original payload.
Data structures like Maps and Sets need similar care. Developers often assume copying a Map protects data, but it only copies the key/value references.
A powerful real-world pattern is immutable updates, where instead of editing data in place, you clone, change the clone, and return it. This avoids mutation chains and keeps your application predictable.
🎯 Pro Pattern: Immutable updates make state changes predictable and prevent cascading mutations across your app.
Reference sharing affects performance. Shallow copies are extremely fast because they only duplicate top-level references. Deep copies recursively duplicate all nested data, meaning the cost grows with data complexity.
Understanding these common pitfalls will save you hours of debugging:
Mastering deep and shallow copying is essential for writing reliable JavaScript:
Good developers write code that avoids unintended side effects. Great developers predict them before they happen. Understanding deep vs shallow copying lets you design safer functions, cleaner components, and more stable architectures.
This is one of the most powerful skills for building production-level apps — and one every serious developer must understand.
Practice quiz
Which of these is stored by value (copied independently on assignment)?
- An object
- An array
- A number
- A Map
Answer: A number. Primitives like numbers are stored by value; objects, arrays, Maps, etc. are stored by reference.
let a = { score: 10 }; let b = a; b.score = 99; What is a.score?
- 99
- 10
- undefined
- Error
Answer: 99. b and a point to the same object reference, so changing b.score also changes a.score to 99.
How much of an object does a shallow copy duplicate?
- Every nested level
- Nothing
- Only nested objects
- Only the top level; nested objects stay shared
Answer: Only the top level; nested objects stay shared. A shallow copy duplicates only the top level and still shares references to nested values.
After const copy = { ...user }; copy.prefs.theme = 'light'; what is user.prefs.theme (started as 'dark')?
- 'dark'
- 'light'
- undefined
- Error
Answer: 'light'. Spread is a shallow copy, so the nested prefs object is shared and the change leaks to user.
Which built-in creates a true deep clone of nested data, Dates, Maps, and circular references?
- structuredClone()
- Object.assign()
- Array.slice()
- JSON.stringify()
Answer: structuredClone(). structuredClone() deep-clones nested objects/arrays and handles Dates, Map, Set, and circular references.
What does JSON.parse(JSON.stringify(obj)) do to a function property?
- Keeps it
- Converts it to a string
- Removes it
- Throws an error
Answer: Removes it. JSON cloning drops functions (and undefined) entirely.
What does JSON cloning turn Infinity into?
- Infinity
- null
- 0
- 'Infinity'
Answer: null. JSON.stringify converts Infinity (and NaN) to null.
What does JSON cloning do to a Date value?
- Keeps it as a Date object
- Removes it
- Throws an error
- Converts it to an ISO string
Answer: Converts it to an ISO string. A Date survives only as a string after JSON.parse(JSON.stringify(...)), losing its Date type.
In the recursive deepClone, what is the base case?
- When the value is an array
- When value is null or typeof value !== 'object' (a primitive)
- When the object is empty
- When depth reaches 10
Answer: When value is null or typeof value !== 'object' (a primitive). Primitives and null are returned as-is; only objects and arrays recurse.
What is the immutable update pattern?
- Edit the original object in place
- Freeze every object
- Clone the data, change the clone, and return it
- Avoid all copying
Answer: Clone the data, change the clone, and return it. Instead of mutating in place, you clone, modify the clone, and return it, keeping state predictable.