Sub topic 1
Primitives, References, and Shared Objects
Prerequisites
This chapter assumes you know JavaScript variables, functions, and scope. You should also be comfortable working with objects and arrays, writing arrow functions, and using ES modules. A basic understanding of strict mode also helps.
Primitives vs. References
Primitives are numbers, strings, booleans, null, undefined, bigint, and symbol. Assigning a primitive copies its value. Assigning an object or array copies only the reference, so both variables point to the same object in memory.
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 valueHow Mutation Leads to Bugs
Every holder of a reference sees a mutation made through any other holder. A function that sorts its argument in place, or a component that edits a shared config object, changes data that other code assumed was stable. These bugs are hard to trace because the code that changes the data and the code that breaks are often far apart. Mutation also defeats change detection that compares references: the object changed, but old === new is still true.
Why const Does Not Make Data Immutable
const stops you from rebinding the variable to a different value. It does nothing to stop changes to the object the variable points to.
const user = { name: 'Ada' };
user.name = 'Grace'; // allowed: the object itself is mutable
console.log(user.name); // 'Grace'
// user = { name: 'Linus' }; // TypeError: Assignment to constant variable.Copying Objects and Arrays with Spread
To change data without mutating it, build a new value. Spread syntax ({ ...obj }, [...arr]) and Object.assign({}, obj) create a new top-level container. Both are shallow copies: nested objects and arrays are still shared by reference.
const original = { name: 'Ada', tags: ['math'] };
const copy = { ...original, name: 'Grace' };
console.log(original.name); // 'Ada'
copy.tags.push('code');
console.log(original.tags); // ['math', 'code'] because the nested array is sharedExercise
After const p = { pos: { x: 0 } }; const q = { ...p }; q.pos.x = 5;, what is p.pos.x, and why?
Show answer
It is 5. The spread copies only the top level, so q.pos and p.pos reference the same nested object.
Exercise
Does declaring const list = [1, 2] prevent list.push(3)?
Show answer
No. const only prevents reassigning list. The array itself stays mutable, so push succeeds.