Understanding Shallow Copy vs Deep Copy in JavaScript
Copying objects in JavaScript isn’t always simple.
There are two types of copying:
Shallow Copy
- Copies only the first level.
- Nested objects are still referenced.
- Changes inside nested objects affect both copies.
Deep Copy
- Copies everything, including nested objects.
- No shared references.
- Changes in one object do not affect the other.
Example
const obj1 = { name: "John", address: { city: "Delhi" } };
const obj2 = { ...obj1 }; // Shallow copy
obj2.address.city = "Mumbai";
console.log(obj1.address.city);
// Mumbai (changed!)
This happens because nested objects are shared.
Simple Explanation
Shallow copy = shared inner objects
Deep copy = completely separate objects

Top comments (0)