Sub topic 1
Primitives, References, and Shared Objects
Immutable data patterns in JavaScript start from one fact: some values are copied when you assign them, and others are shared. Once you can predict which values are shared, you can tell when a change in one place will show up somewhere else. This chapter builds that model. The rest of the tutorial uses it.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript variables (
let,const), functions, and scope - Creating and reading objects and arrays
- Arrow functions and running code in Node.js or a browser console
- Strict mode, at least what
'use strict'turns on
You do not need any library. Every example runs in a current version of Node.js or in a browser.
Two Kinds of Values
JavaScript has seven primitive types and one non-primitive type.
| Category | Types | Example |
|---|---|---|
| Primitive | `string`, `number`, `bigint`, `boolean`, `undefined`, `symbol`, `null` | `'Ada'`, `42`, `10n`, `true` |
| Object | plain objects, arrays, functions, `Date`, `Map`, `Set`, class instances | `{ count: 1 }`, `[1, 2]` |
The two categories behave differently in four places: assignment, function calls, equality checks, and changes.
- A primitive value cannot be changed. Code that looks like it changes a primitive produces a new primitive.
- An object is a container whose contents can change. A variable holding an object does not hold the container itself. It holds a reference, which is a pointer to where the object lives in memory.
The variable for a primitive holds the value. The variable for an object holds a reference to the value. The rest of this chapter follows from that difference.
Assignment Copies Whatever the Variable Holds
Assignment always copies what is stored in the variable. For a primitive, that is the value itself. For an object, that is the reference, so you end up with two references to one object.
const a = { count: 1 };
const b = a;
b.count = 2;
console.log(a.count); // 2, because a and b reference the same object
let x = 1;
let y = x;
y = 2;
console.log(x); // 1, because primitives are copied by valueAfter const b = a, only one object exists. a and b are two names for it. Writing b.count = 2 changes that shared object, so reading through a shows the change.
With x and y, the line y = 2 puts a new value into y. Nothing connects y to x, so x keeps its value.
Reassigning a variable versus changing an object
Keep two operations apart:
- Reassignment (
b = somethingElse) changes what one variable holds. Other variables are unaffected. - Mutation (
b.count = 2,b.push(3),delete b.key) changes the object a reference points to. Every variable holding that reference sees the change.
let a = { count: 1 };
let b = a;
b = { count: 99 }; // reassignment: b now points to a new object
console.log(a.count); // 1, a still points to the original
b = a;
b.count = 50; // mutation: changes the shared object
console.log(a.count); // 50The difference between const and immutability comes down to this same split. A later chapter covers it.
Primitives Really Are Immutable
Strings show the most clearly that primitives cannot be changed. Each string method returns a new string, and writing to an index has no effect.
'use strict';
const name = 'ada';
const upper = name.toUpperCase();
console.log(name); // 'ada', the original is unchanged
console.log(upper); // 'ADA', a new string
try {
name[0] = 'A';
} catch (err) {
console.log(err instanceof TypeError); // true in strict mode
}
console.log(name); // 'ada'Outside strict mode, name[0] = 'A' is silently ignored. In strict mode it throws a TypeError. In both cases the string stays the same. Since a primitive can never change, sharing one between variables is always safe. Two variables holding 'ada' can never affect each other.
Function Arguments Are Shared, Not Copied
JavaScript passes arguments the way it assigns: it copies what the variable holds. People often call this "pass by sharing". For objects, the function receives a copy of the reference. That means:
- Reassigning the parameter inside the function does not affect the caller.
- Mutating the object through the parameter does affect the caller.
function rename(user) {
user.name = 'Grace'; // mutation: visible to the caller
}
function replace(user) {
user = { name: 'Linus' }; // reassignment: local only
}
const person = { name: 'Ada' };
replace(person);
console.log(person.name); // 'Ada'
rename(person);
console.log(person.name); // 'Grace'A common mistake is to believe that JavaScript passes objects "by reference" in the C++ sense. If it did, replace would change person. It does not. The caller's variable and the parameter are separate variables that start out holding the same reference.
The practical result: any function you pass an object to can change your data unless it is careful not to. Every function that receives shared data has to be careful, and immutable patterns take care of that for every one of them.
Equality Compares References for Objects
The === operator compares what the variables hold. For primitives that is the value. For objects that is the reference, which answers "is this the same object?" and not "do these have the same contents?"
console.log('ada' === 'ada'); // true, same value
console.log(1 === 1); // true
const p = { x: 1 };
const q = { x: 1 };
const r = p;
console.log(p === q); // false, two different objects
console.log(p === r); // true, same reference
console.log([1, 2] === [1, 2]); // false
console.log(NaN === NaN); // false, the one primitive exception
console.log(Object.is(NaN, NaN)); // trueReference equality costs very little because it compares two pointers, however large the objects are. Comparing contents means walking through every property. In mutable code, reference equality can give the wrong answer: after p.x = 2, p === r is still true even though the contents changed. Later chapters show how immutability makes reference equality a reliable way to detect changes.
The same rule applies to Set membership, Map keys, and Array.prototype.includes and indexOf when the elements are objects. All of them look for the same reference, not a matching shape.
const items = [{ id: 1 }];
console.log(items.includes({ id: 1 })); // false
console.log(items.some(i => i.id === 1)); // true, compare by content yourselfSharing Hides Inside Containers
References can sit inside other objects. An array of objects holds references, and so does an object whose properties are arrays. Copying the outer container does not copy what is inside it.
const ada = { name: 'Ada' };
const team = [ada];
const sameMember = team[0];
sameMember.name = 'Grace';
console.log(ada.name); // 'Grace'
console.log(team[0].name); // 'Grace'Here three paths (ada, team[0], sameMember) all reach one object. A larger program can have many such paths: a cache, a component's props, an event payload, a module-level constant. If code changes the object through any one path, every other path sees the change. Usually nothing in the source code tells you which paths are connected. The next chapter goes through the bugs this causes.
Edge Cases Worth Knowing
| Situation | Behavior | Why |
|---|---|---|
| `typeof null` | `'object'` | A historical bug. `null` is a primitive. |
| Functions | Shared by reference | Functions are objects and can carry mutable properties. |
| Default parameters like `f(opts = {})` | A new object on each call | The default expression runs again every time the function is called. |
| Object keys | Always strings or symbols | `obj[{}]` uses the key `'[object Object]'`. |
| Destructuring `const { tags } = obj` | `tags` shares the array | Destructuring assigns, and assignment copies references. |
The last row trips people up more than the others. Destructuring and spreading look like copying, but they copy only one level. Anything nested is still shared. That is the subject of the chapter on spread.
Exercise
After running const a = { list: [1] }; const b = a; b.list = [...b.list, 2]; b.list.push(3);, what is a.list, and why?
Show answer
[1, 2, 3]. a and b reference the same object. b.list = [...] changes a property of that shared object, so a.list now points to the new array [1, 2]. push(3) then changes that array, which both variables reach through the same object.
Exercise
A function function reset(cfg) { cfg = {}; } is called as reset(settings). Does settings change? What one-line body would clear the caller's object instead?
Show answer
No. Reassigning the parameter only changes the local variable. To change the caller's object you would mutate it, for example for (const k of Object.keys(cfg)) delete cfg[k];. This mutation is visible to the caller, which is the shared-state behavior immutable patterns avoid.
Exercise
Why does [{ id: 1 }].indexOf({ id: 1 }) return -1, and why is the same check cheap but unreliable when objects are mutated in place?
Show answer
indexOf uses strict equality, which compares references, and the literal { id: 1 } creates a new object. Comparing references is cheap because it is a single pointer comparison. If an object is mutated in place, its reference stays the same while its contents change, so === cannot tell you that anything changed.