While Loops, break and continue
When you do not know how many passes you need, loop on a condition instead of a collection - and make sure something moves it toward false.
Loop while something stays true
The condition is checked before every pass. Something in the body has to change it, or the loop never ends.
Leaving early and skipping a pass
break exits the loop entirely. continue jumps to the next pass.
Staying out of infinite loops
while loop needs three things: a starting value, a condition, and something in the body that moves toward making the condition false.break leaves the loop immediately; the lines after it in the body are skipped, and so is every remaining pass.continue abandons only the current pass. The loop carries on with the next item.While Loops, break and continue: A Practical Guide
Loop on a condition, and know how to get out.
Quick Context
Use a for loop when you know what you are walking through, and a while loop when you do not - when the number of passes depends on something that happens as you go. The condition is tested before each pass, so a while loop whose condition starts false never runs at all.
Infinite loops
A while loop keeps going for exactly as long as its condition stays true, so if nothing in the body changes that condition, it never stops. This is the one beginner mistake that hangs a browser tab - which is why the runner on this site executes your code in a Web Worker and kills it after ten seconds rather than freezing the page.
Interactive Exploration Guide
- Run the first editor. The countdown prints three times, then liftoff. The doubling loop stops at 128 - the first power of two past 100.
- Cause an infinite loop on purpose. Delete
count = count - 1and run. After ten seconds you get Execution timed out instead of a frozen page. Put the line back. - Run the second editor. The break loop stops before printing 4; the continue loop prints only the odd numbers.
- Swap them. Change
breaktocontinuein the first loop and predict the output before running - it should now skip 4 and carry on to 5 and 6.
Key Takeaway
A while loop repeats as long as its condition is true, so the body must move that condition toward false or the loop never ends. break leaves the loop entirely and continue skips just the current pass. Both work in for loops too.