Shallow Copy vs Deep Copy:
1. Shallow Copy
- Copies only the first level of the object/array.
- Nested objects (objects inside objects) are still referenced, not fully copied.
- If you change nested values → both original and copy reflect the change.
✅ Example:
let obj1 = { name: "Dev", address: { city: "Delhi" } };
// Shallow copy using spread operator
let obj2 = { ...obj1 };
obj2.name = "John";
obj2.address.city = "Mumbai";
console.log(obj1.name); // "Dev" (independent)
console.log(obj1.address.city); // "Mumbai" ❌ (changed in both)
2. Deep Copy
- Copies all levels of the object/array.
- Creates completely new objects, not references.
- Changing nested values will not affect the original object.
✅ Example:
let obj1 = { name: "Dev", address: { city: "Delhi" } };
// Deep copy using JSON
let obj2 = JSON.parse(JSON.stringify(obj1));
obj2.name = "John";
obj2.address.city = "Mumbai";
console.log(obj1.name); // "Dev" (independent)
console.log(obj1.address.city); // "Delhi" ✅ (unchanged)
🔹 Summary Table
| Feature | Shallow Copy | Deep Copy |
|---|---|---|
| Copies first level only | ✅ | ❌ |
| Copies nested objects | ❌ (reference kept) | ✅ |
| Changes affect original? | Yes (for nested) | No |
| Methods to create | Spread ..., Object.assign() |
JSON.parse(JSON.stringify()), libraries like Lodash cloneDeep |
🔹 Practical Use Case in MERN
- Shallow copy is enough when you only need to copy top-level values (e.g., updating simple state).
- Deep copy is needed when working with nested state objects in React or MongoDB documents to avoid accidental mutations.