AI Hints
Home›JavaScript Tutorial›JSON and Copying
JavaScript · Lesson 65 of 138

Copying Objects

References and spread.

⏱ 2 min read▶ Video at 1:19:23🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

Copying Objects
From the video: Copying Objects
  • 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.

app.jsjavascript
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);
Output
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.

keyvalue
b = asame object
{ ...a }shallow copy
structuredClone(a)deep copy
a === bsame 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
Next up: Optional Chaining — ?. and ??