Difference Between Shallow Copy and Deep Copy
✅ Shallow Copy
A shallow copy duplicates only the top-level properties of an object.
If the object contains nested objects or arrays, the copy shares references to them.
Example:
const original = {
name: "Teekam",
address: { city: "Delhi" }
};
const shallowCopy = { ...original };
shallowCopy.address.city = "Mumbai";
console.log(original.address.city); // "Mumbai" ❌
✔ Characteristics:
- Copies first level only
- Nested objects are shared
- Faster and lightweight
✔ Ways to create shallow copy:
{ ...obj }
Object.assign({}, obj)
arr.slice()
[...arr]
✅ Deep Copy
A deep copy duplicates all levels of an object, including nested objects.
The copied object is fully independent of the original.
Example:
const original = {
name: "Teekam",
address: { city: "Delhi" }
};
const deepCopy = JSON.parse(JSON.stringify(original));
deepCopy.address.city = "Mumbai";
console.log(original.address.city); // "Delhi" ✔
✔ Characteristics:
- Copies all nested data
- No shared references
- Safer but slower
🔥 Deep Copy Methods
✔ 1. structuredClone() (Best modern way)
const deepCopy = structuredClone(obj);
✔ 2. JSON.parse(JSON.stringify())
✔ Simple
❌ Loses functions, Date, undefined, Map, Set
✔ 3. Custom recursive function
Used when handling complex data types.
🧠 Key Differences Table
| Feature | Shallow Copy | Deep Copy |
|---|---|---|
| Copies | Top-level only | All levels |
| Nested objects | Shared reference | New copy |
| Performance | Fast | Slower |
| Safety | Risky for nested data | Safe |
| Use case | Flat objects | Nested structures |
🎯 Short Interview Answer
A shallow copy copies only the first level of an object and shares references for nested objects.
A deep copy creates a completely independent copy, including all nested objects, preventing unintended mutations.