2.7 — break, continue & nested loops
Loops so far run their full course. Real loops often shouldn’t: you found the item you were searching for — why keep looking? This row of data is corrupt — skip it and carry on. Two escape hatches: break (eject from the whole loop) and continue (abandon this lap only).
And then the multiplier: loops inside loops, which is how programs sweep grids, tables… and test matrices.
for (let i = 1; i <= 6; i++) {
if (i === 4) {
break;
}
console.log(i);
}The track has 6 stations, but watch: laps 1–3 print normally, then at i === 4 the if fires and break EJECTS — the loop is over, instantly. Stations 4, 5, 6? Never visited. The console shows 1 2 3 and life continues after the loop.
The deeper story, with the real names for things — this part is what turns “I saw it” into “I can explain it.”
The nested-loop multiplication table is worth internalizing: outer m laps × inner n laps = m·n executions of the inner body. It is the shape of everything grid-like. Pixels (rows × columns). Calendars (weeks × days). Comparing every item against every other item. In your automation career it appears as the test matrix: 3 browsers × 20 test cases = 60 runs. Add 2 screen sizes and you are at 120. When a CI pipeline takes hours, somewhere inside is a nested loop that someone forgot was multiplying.
About that “innermost only” rule: JavaScript does have an escape. You can label a loop (outer: for (…)) and write break outer; to exit both levels at once. It is legal, rare, and worth recognizing more than writing.
If you need labels often, the code is usually asking to be reorganized into a function. Phase 3 gives you that tool — and there, return is the cleanest escape of all.
Fun fact: break and continue are the tamed descendants of a notorious ancestor: goto, an old command that let programs jump to ANY line. The result was called spaghetti code — tangled, and nearly impossible to follow. break, continue and return are the disciplined version that survived. Loops with one entrance, and only clearly-marked exits.
✏️ Quick check 1
Which keyword abandons only the CURRENT lap and keeps looping? Type it.
✏️ Quick check 2
found() first says true at i = 2. How many laps run? Type the number.
for (let i = 0; i < 100; i++) {
if (found(i)) { break; }
}✏️ Quick check 3
Your test suite runs 25 test cases across 4 browsers using nested loops. The inner body runs how many times in total? Type the number.
🗣️ Now teach it back
Explain to a friend: break vs continue (ejector seat vs skip ramp), how nested loops multiply, and which loop a break inside a nested loop actually escapes.
Write it as if your friend is sitting next to you. Saved to your journal — future-you will use these notes to teach others.