Sub topic 2
Values Versus References
This chapter assumes you can declare variables with let and const, write and call functions, and create object and array literals. You should also be able to run snippets in a browser console or Node.js. The previous chapter listed the seven primitive types and the object type. This one explains how each kind behaves when you assign it, pass it to a function, or compare it.
The Working Model
A variable holds a value. If that value is a primitive (string, number, bigint, boolean, undefined, null, or symbol), the variable holds the primitive itself. If the value is an object, which includes arrays, functions, dates, and maps, the variable holds a reference. A reference is a pointer to an object stored somewhere else in memory.
Assignment always copies whatever the variable holds. Copying a primitive gives you an independent value. Copying a reference gives you a second pointer to the same object.
let a = 5;
let b = a;
b = 10;
console.log(a); // 5: primitives are copied by value
const obj1 = { count: 5 };
const obj2 = obj1;
obj2.count = 10;
console.log(obj1.count); // 10: both names refer to the same object
console.log({ x: 1 } === { x: 1 }); // false: different objectsPrimitives Are Immutable
You cannot change a primitive in place. Every operation that looks like it modifies one creates a new value.
let greeting = "hello";
const upper = greeting.toUpperCase();
console.log(greeting); // "hello": the original is unchanged
console.log(upper); // "HELLO": a new string
greeting[0] = "J"; // silently ignored (TypeError in strict mode)
console.log(greeting); // "hello"
greeting = "J" + greeting.slice(1);
console.log(greeting); // "Jello": the variable now holds a new stringImmutability is the reason value semantics are safe for primitives. Two variables that hold the string "hello" cannot affect each other, because neither one can change the string.
Mutation Versus Reassignment
Most reference bugs come from mixing up two different operations:
| Operation | Example | What changes | Visible through other references? |
|---|---|---|---|
| Reassignment | `obj2 = { count: 0 }` | The variable now points elsewhere | No |
| Mutation | `obj2.count = 0` | The object itself | Yes |
const original = { count: 1 };
let alias = original;
alias.count = 2; // mutation
console.log(original); // { count: 2 }
alias = { count: 99 }; // reassignment
console.log(original); // { count: 2 }: original is unaffected
console.log(alias); // { count: 99 }Passing Arguments to Functions
JavaScript passes every argument by value. When the argument is an object, the value that gets copied is the reference. People call this "call by sharing": the function receives its own copy of the pointer. That means:
- Mutating the parameter changes the caller's object.
- Reassigning the parameter has no effect on the caller.
function addItem(cart) {
cart.items.push("apple"); // mutates the shared object
}
function resetCart(cart) {
cart = { items: [] }; // rebinds the local parameter only
}
const myCart = { items: [] };
addItem(myCart);
console.log(myCart.items); // ["apple"]
resetCart(myCart);
console.log(myCart.items); // ["apple"]: unchanged by reassignmentIf a function has to "replace" the caller's object, it should return the new object, and the caller should assign it: myCart = resetCart(myCart).
Identity Comparison
=== and == compare objects by identity. Two references are equal only when they point to the same object. Contents are never examined. Arrays behave the same way.
const p = { x: 1 };
const q = { x: 1 };
const r = p;
console.log(p === q); // false: same contents, different objects
console.log(p === r); // true: same object
console.log([] === []); // false
console.log([1, 2].includes([1, 2])); // false: includes also uses identity for objectsIdentity comparison also affects Set, Map keys, and indexOf. A Set will hold two { x: 1 } objects as separate entries. If you need structural equality, write a comparison function or compare a serialized form such as JSON.stringify. Serialization only works when key order is consistent and every value can be serialized.
Copying Objects: Shallow and Deep
Spread syntax, Object.assign, Array.prototype.slice, and Array.from make shallow copies. A shallow copy creates a new outer object, but nested objects are still shared.
const settings = { theme: "dark", layout: { columns: 2 } };
const shallow = { ...settings };
shallow.theme = "light";
shallow.layout.columns = 3;
console.log(settings.theme); // "dark": top level was copied
console.log(settings.layout.columns); // 3: nested object is shared
const deep = structuredClone(settings);
deep.layout.columns = 4;
console.log(settings.layout.columns); // 3: fully independentEdge Cases in Copying
| Technique | Depth | Limitations |
|---|---|---|
| `{ ...obj }`, `Object.assign` | Shallow | Copies only own enumerable properties; getters are evaluated, not copied |
| `[...arr]`, `arr.slice()` | Shallow | Nested arrays and objects stay shared |
| `JSON.parse(JSON.stringify(x))` | Deep | Drops `undefined`, functions, and symbols; turns `Date` into a string; throws on BigInt and on circular references |
| `structuredClone(x)` | Deep | Handles `Date`, `Map`, `Set`, and cycles; throws on functions and DOM nodes; drops prototypes, so class instances become plain objects |
const node = { name: "root" };
node.self = node; // circular reference
const cloned = structuredClone(node);
console.log(cloned.self === cloned); // true: the cycle is preserved
console.log(cloned === node); // falseFreezing Is Shallow
Object.freeze blocks adding, removing, and changing an object's own properties. Nested objects can still be mutated unless you freeze them as well.
"use strict";
const config = Object.freeze({ port: 8080, db: { host: "localhost" } });
try {
config.port = 3000;
} catch (e) {
console.log(e instanceof TypeError); // true in strict mode
}
config.db.host = "example.com"; // allowed: db itself is not frozen
console.log(config.db.host); // "example.com"In sloppy (non-strict) mode, a write to a frozen property fails without an error. That silent failure is a common source of confusion.
Common Errors
- Defaulting with a shared object.
const DEFAULTS = { tags: [] }followed byconst opts = { ...DEFAULTS }sharestagsacross every caller. Copy the nested values, or build defaults inside a function. Array(n).fill({}). This fills every slot with the same object. UseArray.from({ length: n }, () => ({}))to get separate objects.- Sorting in place.
sort,reverse, andsplicemutate the array that callers passed in. UsetoSorted,toReversed, andtoSpliced(ES2023) or copy the array first. - Expecting
===to compare contents. It never does for objects.
const grid = Array(3).fill([]);
grid[0].push("x");
console.log(grid); // [["x"], ["x"], ["x"]]: one array, three references
const fixed = Array.from({ length: 3 }, () => []);
fixed[0].push("x");
console.log(fixed); // [["x"], [], []]This identity model comes up again in later chapters. When an object takes part in equality or arithmetic, JavaScript has to decide whether to compare references or to convert the object to a primitive first.
Exercise
After running const a = { n: 1 }; const b = a; b.n = 2; let c = b; c = { n: 3 };, what are a.n, b.n, and c.n, and what is a === b?
Show answer
a.n is 2, b.n is 2, c.n is 3, and a === b is true. b.n = 2 mutates the single object that a and b share. c = { n: 3 } reassigns only c, so it does not affect that object.
Exercise
A function function clear(list) { list = []; } is called as clear(items), but items keeps its elements. Explain why, and give two ways to make the function empty the caller's array.
Show answer
The parameter list holds a copy of the reference. Reassigning it points only the local variable at a new array. To fix it, either mutate the shared array (list.length = 0 or list.splice(0)), or return a new array and have the caller reassign it: items = clear(items).
Exercise
const copy = { ...user } is followed by copy.address.city = "Oslo". Does user.address.city change? Which call would prevent it, and when would that call throw?
Show answer
Yes. Spread makes a shallow copy, so copy.address and user.address are the same object. structuredClone(user) makes a deep, independent copy. It throws if user contains a function or another value that cannot be cloned, such as a DOM node.