The difference between shallow copy and deep copy mainly revolves around how nested objects (or references) are copied. Let’s break it down clearly:
1. Shallow Copy
- Definition: Creates a new object, but the top-level elements only are copied. If the object contains nested objects (like arrays, objects), the copy shares references to the same nested objects instead of creating new ones.
- Effect: Changes in nested objects affect both the original and the copied object.
- Methods in JavaScript:
Object.assign({}, obj)- Spread operator:
{ ...obj } - Array:
[...arr]
Example:
let original = { a: 1, b: { c: 2 } };
let shallow = { ...original };
shallow.a = 10; // Only shallow copy is affected
shallow.b.c = 20; // Both original and shallow are affected
console.log(original.b.c); // 20
2. Deep Copy
- Definition: Creates a completely independent copy of the object, including all nested objects. Changes in the copy do not affect the original object.
- Effect: No shared references; fully independent.
- Methods in JavaScript:
JSON.parse(JSON.stringify(obj))(simple objects)- Using libraries like Lodash:
_.cloneDeep(obj)
Example:
let original = { a: 1, b: { c: 2 } };
let deep = JSON.parse(JSON.stringify(original));
deep.b.c = 20;
console.log(original.b.c); // 2 (original unaffected)
Summary Table
| Feature | Shallow Copy | Deep Copy |
|---|---|---|
| Copies nested objects? | No, only references | Yes, fully independent |
| Effect on original if nested changes | Changes reflect | No effect |
| Performance | Faster (less memory) | Slower (more memory) |
| Methods | Object.assign, ... | JSON.parse(JSON.stringify), _.cloneDeep |
