Loops — for, while, do...while, and labelled break¶
Level: 101 · for anyone who has written a loop in another language
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: do...while always runs its body once, a plain break leaves only the innermost loop, and break outer leaves every loop out to the label — a label even lets break leave a plain block, though continue must name a loop.
Keywords: for, while, do...while, break, continue, label
What the finished page will answer¶
- How many times does
do { ... } while (false)run its body, and how many times doeswhile (false) { ... }? - In two nested loops, which loop does a plain
breakleave, and which doesbreak outerleave? - Why does a
continueplaced beforei++in awhileloop spin forever, when the samecontinuein aforloop still runs the update? - What does
breakdo inside a labelled block that is not a loop, and why iscontinueto that label aSyntaxError? - What does
for (let i = 0, j = 9; i < j; i++, j--)visit, and what doesfor (;;)do?
Examples it will need¶
-
loops_break_and_labels_js.js— the pairs a nested search visits withbreak, withbreak outerand with a labelled block -
loops_continue_in_while_js.js—continuein aforloop beside the samecontinuein awhileloop, the second stopped by a guard after 20 turns -
loops_continue_label_sh.sh— the SyntaxError forcontinuenaming a block label, and for a label that does not exist
See also¶
- Closures in loops — a
letin aforheader is a new variable every turn for...inandfor...of— the two loops that walk keys and values for youmap,filter,reduceand friends — array methods that replace many counting loops- Blocking the event loop — what a long loop does to every timer
- Rust: Loop labels ↗ — the same labelled
break, spelled'outerin Rust - Rust:
break↗ — in Rustbreakcan carry a value out of a loop