Shallow vs Deep Copy
You'll learn: How shallow copies handle references differently than deep copies, and when each approach is appropriate for your data structures.
What's the Difference?
A shallow copy duplicates only the top level of an object or array. If your data contains nested objects or arrays, the copy will share references to those nested structures with the original. Change a nested value in the copy, and you'll change it in the original too.
A deep copy recursively duplicates everything, creating entirely independent nested structures. No shared references means complete isolation between original and copy.
Shallow Copy Techniques
The spread operator ({...obj}) and Object.assign() both create shallow copies:
const original = { name: 'Alice', address: { city: 'Boston' } };
const shallow = { ...original };
shallow.name = 'Bob'; // ✓ Safe, only affects shallow
shallow.address.city = 'NYC'; // ✗ Changes original too!
console.log(original.address.city); // 'NYC' — surprise!
Think of it like: Photocopying a document that contains a reference card. You get a new document, but both documents point to the same reference card.
When Each Matters
- Shallow copies work fine for flat objects with primitive values only
- Deep copies are essential when you have nested objects/arrays and need true independence
- Performance: shallow copies are faster; deep copies can be expensive with large, complex structures
Key Takeaway: Shallow copies (..., Object.assign) duplicate the surface but share nested references, while deep copies create fully independent clones—choose based on your data's nesting and mutation needs.