awesome-everything RU
↑ Back to the climb

Base CS from zero

Variables and state: code reading

Crux Read short TypeScript snippets — aliasing, copy vs reference, scope shadowing, and a swap — and predict exactly what value each variable holds and why.
Your altitude — climbing toward senior
ZeroJuniorMiddleSenior
You are at middle altitude — in the sky
◷ 14 min

The fastest way to find out whether the memory model has clicked is to trace real code by hand. For each snippet, follow the cells: what is the value, what is a reference, which binding does a name resolve to, and which writes are mutations to a shared object. Predict the output before you read the options.

Goal

Practise tracing what every variable holds after each line — distinguishing a copied primitive from a shared reference, an inner binding from an outer one, and an in-place mutation from a fresh allocation.

Snippet 1 — the shared object

const original = { count: 0 };
const copy = original;       // assigns the reference, not the object
copy.count = 5;              // mutate through copy
console.log(original.count); // ?
Quiz

What does the final line print, and why?

Snippet 2 — primitive vs object side by side

let n = 10;
let m = n;          // copies the value 10
m = m + 1;          // changes m's own cell

let p = { v: 10 };
let q = p;          // copies the reference
q.v = q.v + 1;      // mutates the shared object

console.log(n, q === p, p.v); // ?
Quiz

What is printed?

Snippet 3 — scope shadowing

let x = 1;
{
  let x = 2;        // a new binding in the inner block
  x = x + 10;       // writes to the inner x's cell
  console.log(x);   // inner
}
console.log(x);     // outer
Quiz

What do the two console.log lines print, in order?

Snippet 4 — the swap

let a = 1;
let b = 2;
a = b;
b = a;
console.log(a, b);  // ?
Quiz

What is printed, and what is the fix if the intent was to swap a and b?

Recap

Tracing by hand is the whole skill: a copied primitive (m, n) lives in its own cell and ignores changes to the other; a copied reference (p, q) makes both names alias one object so a mutation propagates and === is true; an inner ‘let’ creates a new binding that shadows the outer name without touching its cell; and a naive ‘a = b; b = a’ fails because each assignment is a destructive overwrite, which is why a real swap needs a temporary. Follow the cells and the answer is never a surprise.

Continue the climb ↑Variables and state: build a state container
shortcuts expand
search
K
prev piece
k
next piece
j
cycle tier
t
this menu
?
sources2
expand
  1. 01
  2. 02

Trademarks belong to their respective owners. Editorial reference only.