Course outline · 0% complete

0/27 lessons0%

Course overview →

Copies vs references, and the final gauntlet

lesson 10-3 · ~12 min · 27/27

What assignment actually copies

  • Primitives (numbers, strings, booleans, null, undefined, symbols, bigints) are copied by value. Two variables, two independent values.
  • Objects (including arrays and functions) are copied by reference: the variable does not contain the object, it contains a reference — the object's location in memory — and assignment copies that reference, so both variables end up naming one shared object. (If it helps, picture the reference as an arrow: b = a copies the arrow, not the thing it points at.)

Consequences interviewers probe: const only locks the reference, so const arr = [] can still be pushed to. Spread ({ ...obj }, lesson 8-2) copies one level only, nested objects stay shared. structuredClone(obj) makes a true deep copy.

This distinction sits behind a huge share of real bugs — the function that "mysteriously" edits its caller's data, the UI state that never re-renders because the reference never changed. It is also the single most reliable interview filter there is.

variablesn = 5a ●b ●one shared object{ items: [1, 2] }n owns its value. a and b hold arrows to the SAME object.
Assignment copies what the variable holds: a value for primitives, an arrow for objects. b = a duplicates the arrow, not the object.

Code exercise · javascript

Run it. b and a share one object, the spread copy shares the nested array (shallow), and only structuredClone is fully independent.

Quiz

`const team = ["Ada"];` Which line throws an error?

Code exercise · javascript

Your turn. `withDiscount` must NOT modify the original order, but it does. Fix it so the function builds an independent copy first (spread is enough here, one level deep), applies the discount to the copy, and the original price stays 100.

You made it

The interview map you now carry: closures capture variables (unit 1), this is decided by the call (unit 2), methods live on prototypes (unit 3), the event loop drains microtasks before macrotasks (unit 4), promises chain and reject downward (unit 5), Promise.all runs independent work in parallel (unit 6), generators pause (unit 7), spread copies shallowly (units 8 and 10), regex needs anchors (unit 9), and var hoists to undefined (unit 10).

One last classic below. Say your reasoning out loud, exactly like you should in the real interview.

Problem

Final gauntlet. What number does this print: ```javascript const arr = [1, 2, 3]; const copy = arr; copy.push(4); console.log(arr.length); ```