awesome-everything RU
↑ Back to the climb

Base CS from zero

Control flow: trace the code

Crux Read four small programs and trace them by hand: predict loop counts and outputs, spot an off-by-one boundary, and reason about short-circuit evaluation as chained conditional jumps.
Your altitude — climbing toward senior
ZeroJuniorMiddleSenior
You are at middle altitude — in the sky
◷ 14 min

The only reliable way to know what a branch or loop does is to trace it the way the CPU does: follow the program counter and the variables, one step at a time. Read each snippet, predict the outcome by hand, then check yourself.

Goal

Practise the core skill of the unit: step through conditionals and loops by hand, count iterations exactly, find the off-by-one that flips a boundary, and reason about short-circuit evaluation as the chained conditional jumps it compiles to.

Snippet 1 — count the iterations

let count = 0;
let i = 1;
while (i <= 5) {   // note: <= , not <
  count++;
  i++;
}
// what is count?
Quiz

What is the final value of count?

Snippet 2 — the off-by-one boundary

const a = [10, 20, 30];   // length 3, valid indices 0,1,2
let i = 0;
while (i <= a.length) {   // <= length, not < length
  console.log(a[i]);
  i++;
}
Quiz

How many times does the loop body run, and what is the bug?

Snippet 3 — short-circuit as chained jumps

function check(user) {
  // && stops at the first falsy operand
  if (user && user.active && user.age >= 18) {
    return "allowed";
  }
  return "denied";
}
check(null);   // user is null
Quiz

check(null) returns 'denied'. Why does user.active never get evaluated, in machine-level terms?

Snippet 4 — nested loop and conditional

let sum = 0;
for (let i = 0; i < 3; i++) {     // outer: i = 0,1,2
  for (let j = 0; j < 3; j++) {   // inner: j = 0,1,2
    if (i === j) {                // only the diagonal
      sum += 1;
    }
  }
}
// what is sum?
Quiz

What is the final value of sum?

Recap

Tracing by hand is the whole skill. A loop’s count is exactly how many times its test stays true — and the boundary operator (&lt; vs &lt;=) is where off-by-one bugs live, here reading one element past the end of a 3-element array. Short-circuit && compiles to chained conditional jumps that bail to the false path the moment an operand is falsy, which is why later operands are never even read (and why a null check guards the reads after it). Nested loops multiply iteration counts, but a guarding if still only fires when its own condition holds. When in doubt, walk the program counter and the variables one step at a time.

Continue the climb ↑Control flow: build a jump machine
shortcuts expand
search
K
prev piece
k
next piece
j
cycle tier
t
this menu
?
sources3
expand
  1. 01
  2. 02
  3. 03

Trademarks belong to their respective owners. Editorial reference only.