Course outline · 0% complete

0/29 lessons0%

Course overview →

References: two names, one object

lesson 5-4 · ~9 min · 17/29

Assignment copies the reference, not the object

This lesson exists because the most confusing bug class in JavaScript is two variables secretly sharing one object. The actual rule: a variable never contains an object directly — it contains a reference, the object's address in memory. So const b = a copies the address, not the data. Afterward a and b point at the same object; change it through either name and the other sees it, because there is only one object.

Numbers, strings, and booleans do NOT behave this way: assigning them copies the value itself. Only objects and arrays (arrays are objects) are shared by reference.

The same rule explains === on objects: it compares references — "same object in memory?" — not contents. { a: 1 } === { a: 1 } is false: two separate objects that merely look alike.

To copy for real, build a new object or array: { ...obj } and [...xs] spread the contents into a fresh one. One warning: spread makes a shallow copy, one level deep, so objects nested inside are still shared. For a fully independent copy of nested data, use structuredClone(obj).

Python lists and dicts behave identically, so you may have met this bug before under the name aliasing.

ab{ score: 99 }one object in memory
const b = a copies only the arrow. Both variables hold a reference to the same object, so an edit made through b is visible through a.

Code exercise · javascript

Run it. b = a copies the arrow, so changing b.score changes the one shared object a also points at. The last line builds two separate objects with identical contents — === still says false, because they are different objects.

Code exercise · javascript

Your turn. This program has the classic bug: userSettings was "copied" with =, so editing it corrupts defaults too. Fix ONE line with spread so the output becomes 14 then 18.

Quiz

const a = [1, 2]; const b = a; b.push(3); What is a.length now?