Shallow copy vs deep copy — what does spread copy?
Answer out loud or in your head first, then compare.
Answer
Spread copies only the first level. Nested objects stay shared.
JavaScript
const original = { profile: { name: 'Anna' } };
const shallow = { ...original };
const deep = structuredClone(original);
shallow.profile.name = 'Ola';
console.log(original.profile.name); // Ola
console.log(deep.profile.name); // AnnaTo be precise: structuredClone handles many data types and cycles, but not functions or every kind of object.
Pitfall: JSON stringify/parse loses some information and doesn't handle cycles. In React it's often enough to copy just the path you change, instead of deep-cloning the whole state.
How did it go? Be honest — “Not yet” puts the question on your review list.
Related questions
- B-P09 · What does changing an object by reference mean, and why do we copy state? — JavaScript, TypeScript and Node.js
- Spread and a nested object — JavaScript