Control Flow

Difficulty
Importance

The problem

Real tasks require doing different things depending on conditions and repeating steps until a goal is met — without a way to branch and repeat, a program is just a single straight-line sequence of steps with no ability to react or scale to arbitrary input size.

Why now

Variables and state give us something that can change, but nothing yet decides when it changes or how many times. Control flow is the mechanism that lets a boolean condition (sets-and-logic) actually steer execution — turning a static list of instructions into a program that responds to its input.

Mental model

All control flow reduces to two moves: branch (do A or B, based on a condition) and repeat (do A again while a condition holds). Every loop is a conditional branch that jumps backwards; every recursive call, exception, and early return is a more disciplined way of doing the same two things.

Requires

Unlocks

Parallel

Used in

Projects

  • Rewrite a for-loop as a while-loop and then as recursion, keeping behavior identical, to see the same control-flow idea in three shapes
  • Implement FizzBuzz and identify exactly which lines are 'branch' and which are 'repeat'

Examples

  • for (let i = 0; i < 10; i++) is a repeat: initialize state, test a condition, mutate state, repeat
  • A guard clause (if (!isValid) return;) is a branch that short-circuits the rest of a function

Resources

Mastery checklist