Control Flow
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
- Sets & LogicMathematical Thinking
Branches and loop conditions are boolean propositions; without propositional logic, 'if' and 'while' have nothing to test.
- Variables & StateProgramming Fundamentals
A loop needs state that changes each iteration (a counter, an accumulator) — control flow without mutable state can only branch once, never repeat meaningfully.
Unlocks
Parallel
Used in
- if/else, for, while, switch in every imperative language
- Routing logic in web frameworks (branch on URL/method)
- Retry loops and polling in distributed systems clients
- State machines (a formalization of structured control flow)
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
- I can identify the branch and repeat primitives inside any loop or conditional
- I can rewrite a for-loop as an equivalent while-loop
- I can explain why a loop needs mutable state to make progress
- I can trace the exact execution order of nested branches and loops by hand