JavaScript
/Intermediate
Shallow vs Deep Copy
Definition
A Shallow Copy duplicates the top level of an object, but nested objects are still passed by reference. A Deep Copy creates a completely independent clone of the object and all its nested properties.
Explain Like I'm New
Shallow copy is taking a photo of a family. You get a new photo, but the people in it are the same people. If the real dad dyes his hair red, the photo dad doesn't change, but wait... in JS memory, they DO change! Deep copy is literally cloning the entire family in a lab so you have two completely separate sets of humans.
Real World Example
Using the spread operator `{ ...user }` (Shallow) to update state in React. Using `structuredClone(user)` (Deep) to create a backup of a massive nested form state before the user edits it.
Common Use Cases
- •Immutability in React/Redux
- •Data backups
Interactive Example
Loading...
Console output will appear here...
Interview Questions
basic
- Is the Spread Operator `...` a shallow or deep copy?
intermediate
- What is wrong with using `JSON.parse(JSON.stringify(obj))` for deep cloning?
advanced
- What is `structuredClone()`?