Copy a customer’s record four ways, spread, Object.assign, the JSON trick and structuredClone, then change the copy: does the original change too, and what…
Why it matters
One of the sneakiest sources of state bugs: you think you made a copy, but the objects inside are still shared. In React especially, mutating a spread copy’s insides silently damages the old state. Knowing shallow from deep means safe state updates.
The key idea
Spread is SHALLOW: the boxes inside are shared, not copied
Common mistakes
Change an object inside the copy, and the original changes too{ ...obj } copies only the top layer. Objects and arrays inside are still the same boxes. Use structuredClone, or copy the layer you change.
A date turns into text after a "deep copy" through JSON A Date becomes text, undefined and functions vanish, Map and Set become {}, a loop throws. Use structuredClone.
structuredClone throws a DataCloneError Functions, DOM elements and symbols cannot be cloned. Copy the data alone, without methods.
Try it in this playground
Copy with { ...asli }, then change a box inside salinan.alamat.kota = 'Batu' changes the original too: box #2 is shared.
Switch to structuredClone, try again Now the original stays: every layer has a box of its own.
Try JSON.parse(JSON.stringify()) Deep too, but look at salinan.buka: the Date became text.
Copy a record with a method or an element structuredClone refuses it: a DataCloneError.