While Loops & Loop Control

Learn while loops for when you don't know how many times to repeat, plus break and continue for fine-grained loop control.

Step 1 of 5

When you don't know the count in advance

A `for` loop is perfect when you know exactly how many times to repeat: 'do this 10 times' or 'do this for every item in the array.' But sometimes you don't know the count in advance. You just know when to stop.

Examples: - Keep asking for a password **while** the user enters the wrong one - Keep scrolling the feed **while** there are more posts to load - Keep dealing cards **while** the player wants to hit

The `while` loop checks a condition before each iteration. As long as the condition is `true`, the body keeps running. The moment it becomes `false`, the loop stops.

Think of it this way: A while loop is like waiting for a bus: 'While the bus hasn't arrived, keep waiting.' You don't know if it'll take 2 minutes or 20 — you just keep checking until the condition changes.
Tip: Infinite loop danger!
Always make sure the condition will eventually become `false`, or you'll create an infinite loop that freezes the browser tab! The most common mistake is forgetting to update the variable that the condition checks. If you write `while (count < 10)` but never increase `count`, the loop runs forever.
Learn more on MDN
JAVASCRIPTREAD ONLY
CONSOLE
Click "Run" to execute your code...