Control Flow

How a program decides what to do next: branching with if and switch, choosing a value with the ternary, repeating work with the four loop forms, and steering a loop with break, continue and labels. Plus when to delete a branch entirely and use a lookup.

What you will be able to do

  • Choose between if/else, a ternary, a switch and a lookup on purpose
  • Flatten nested conditionals with early returns
  • Pick the right loop for the job, and say what each one gives you
  • Explain why for...in is wrong for arrays and why forEach cannot break
  • Escape a nested loop with a labelled break, or avoid needing one

Lessons

  1. Conditionals — A statement picks a path; an expression produces a value. Choose the one that matches what you actually need. (10 min)
  2. Loops — Every loop answers two questions: what do I get each time round, and what makes it stop? (13 min)
  3. break, continue and Labels — break leaves the loop, continue skips to the next pass, and a label says which loop you meant. (9 min)