Shallow copy
A shallow copy duplicates only the top-level properties. If those properties are references (like objects or arrays), the copy will reference the same objects.
let original = { a: 1, b: { c: 2 } }
let copy = { ...original }
copy.b.c = 3 // Changes "original.b.c"
When to use:
- Small objects with primitive data types.
- Situations where performance is critical.
- Cases where changes to nested objects should reflect in all copies.
Deep copy
A deep copy creates a complete clone of the original object, duplicating all nested objects and arrays.
let original = { a: 1, b: { c: 2 } }
let copy = JSON.parse(JSON.stringify(original));
copy.b.c = 3 // The "original.b.c" remains 2
When to use:
- Complex objects with nested structures.
- Scenarios where complete independence from the original object is needed.
- Preventing unintended side-effects from shared references.