Value vs Reference
Primitives are copied when you pass them around and objects are shared, which is the root cause of a large share of confusing bugs.
A variable holding an object holds an address, not the object. Assigning, passing to a function and storing in an array all copy the address. Equality compares addresses, so two identical objects are never equal.
EXERCISE
1What a Variable Actually Holds
For a primitive the variable holds the value; for an object it holds the address of the value.
You met this in Unit 2. Now that you are working with objects properly, it is worth seeing all of its consequences in one place.
Primitives: the value is in the box:
let a = 10;
let b = a; // copy the value
b = 20;
console.log(a, b); // 10 20 two independent boxes
Objects: the address is in the box:
const x = { count: 10 };
const y = x; // copy the ADDRESS
y.count = 20;
console.log(x.count, y.count); // 20 20 one object, two labels
Three ways the same object gets shared:
const original = { n: 1 };
// 1. Assignment
const copy = original;
// 2. Passing to a function
function change(obj) {
obj.n = 99;
}
change(original);
console.log(original.n); // 99
// 3. Putting it in an array or another object
const list = [original];
list[0].n = 500;
console.log(original.n); // 500
Arrays behave identically, because arrays are objects:
const items = [1, 2, 3];
const alias = items;
alias.push(4);
console.log(items); // [ 1, 2, 3, 4 ]
Pro Tip: When a value changes and you cannot see where, ask whether it is an object and how many names point at it. The answer is nearly always that something you thought was a copy was an alias. Primitives never have this problem, which is why bugs of this kind only ever involve objects, arrays, dates and functions.
EXERCISE
2Equality Compares Addresses
Two objects with identical contents are not equal, because the comparison asks whether they are the same object.
The rule, and its consequences:
const a = { name: "Ada" };
const b = { name: "Ada" };
const c = a;
console.log(a === b); // false different objects
console.log(a === c); // true same object
console.log(a == b); // false == does not help
Which is why these common checks fail:
const items = [];
console.log(items === []); // false
console.log(items.length === 0); // true <- check this instead
const users = [{ id: 1 }];
console.log(users.includes({ id: 1 })); // false
console.log(users.some((u) => u.id === 1)); // true <- use a test
Comparing contents means comparing the parts:
const a = { id: 1, name: "Ada" };
const b = { id: 1, name: "Ada" };
console.log(a.id === b.id && a.name === b.name); // true
// For small, flat, plain objects:
console.log(JSON.stringify(a) === JSON.stringify(b)); // true
// That trick breaks on key order, dates, undefined values
// and functions, so keep it for quick checks only.
console.log(JSON.stringify({ x: 1, y: 2 }) === JSON.stringify({ y: 2, x: 1 }));
// false, although the two objects hold the same data.
Comparing by a stable id is what real code does:
const selected = { id: 2, name: "Grace" };
const users = [{ id: 1 }, { id: 2 }, { id: 3 }];
const found = users.find((u) => u.id === selected.id);
console.log(found); // { id: 2 }
There is no deep equality built into , and that is deliberate, because "the same data" means different things in different programs. In practice you compare by an id, or you compare the specific fields that matter. Reaching for a library such as lodash's isEqual is reasonable when you genuinely need a general answer.
EXERCISE
3When Sharing Is Right and When It Bites
Shared references are a feature, and the trouble comes from sharing something without meaning to.
Sharing on purpose, which is normal and useful:
const currentUser = { name: "Ada", unread: 3 };
function markAllRead(user) {
user.unread = 0;
}
markAllRead(currentUser);
console.log(currentUser.unread); // 0 exactly as intended
The function name says it changes something, so the caller is not surprised.
Sharing by accident, which is the bug:
const defaults = { theme: "dark", fontSize: 14 };
const userSettings = defaults; // meant as a starting point
userSettings.fontSize = 18;
console.log(defaults.fontSize); // 18 <- the defaults are gone
// Every future user now starts at 18.
The same bug hidden inside a function:
const blank = { items: [], total: 0 };
function newOrder() {
return blank; // hands out the SAME object every time
}
const o1 = newOrder();
const o2 = newOrder();
o1.total = 100;
console.log(o2.total); // 100 <- two orders, one object
function newOrderProperly() {
return { items: [], total: 0 }; // a fresh object each call
}
A nested array in a shared object:
const template = { tags: [] };
const a = { ...template };
const b = { ...template };
a.tags.push("urgent");
console.log(b.tags); // [ 'urgent' ] <- the copy was only one level deep
The next lesson covers exactly that problem and how to avoid it.
Pro Tip: A function that hands back the same object every time it is called is a bug waiting to happen, and it reads as perfectly reasonable code. If a function is supposed to produce a fresh thing, it must build a fresh thing inside itself, not return one that was made once and lives outside.
