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.
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.
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.