Copying Objects
References and spread.
Here's something that surprises almost everyone. When you assign an object to a new variable, you don't get a copy. You get a second name for the same object. Change one, and you change both.

- Assigning doesn't copy
- Two names, one object
- Change one, change both
References
B equals A just makes B point to the same object. So changing B's name changes A's name too. Spread makes a real copy of the top level. But nested objects are still shared, so changing the copy's address changes the original's address. Structured clone makes a full, deep copy. Run it.
const a = { name: "Ana", address: { city: "Lisbon" } };
const b = a;
b.name = "Bea";
console.log(a.name);
const c = { ...a };
c.name = "Cara";
c.address.city = "Porto";
console.log(a.name, a.address.city);
const d = structuredClone(a);
d.address.city = "Faro";
console.log(a.address.city, d.address.city);Bea Bea Porto Porto Faro
Shallow and deep
A shallow copy, with spread, copies the top level, but shares anything nested. A deep copy, with structured clone, copies everything, all the way down. Comparing objects with three equals checks whether they're the same object, not whether they look the same.
| key | value |
|---|---|
| b = a | same object |
| { ...a } | shallow copy |
| structuredClone(a) | deep copy |
| a === b | same object? |
Summary
Assigning an object shares it. Spread makes a shallow copy, and structured clone makes a deep copy. Next, safely reading values that might be missing.
Key takeaways- Assignment shares
- Spread: shallow
- structuredClone: deep