The JavaScript while statement
The while loop runs a block over and over as long as its condition is true, checking before each pass. while (i < 10) { ... }. Use it when you don't know the number of iterations in advance. Make sure something inside changes the condition, or you get an infinite loop.
Overview
A while loop keeps running its body for as long as the condition is true, testing it before every pass. It shines when you don't know up front how many times you'll loop — reading until input runs out, retrying until something succeeds, processing a queue until it's empty. If the condition is false to begin with, the body never runs at all.
The hazard to respect is the infinite loop. Something inside the body must eventually make the condition false — increment a counter, shrink a list, flip a flag. Forget that and the loop runs forever, freezing the page. It's the single most common while bug, so always check that the exit condition is reachable.
Its close relative do...while puts the check at the end, so the body always runs at least once — handy for things like prompting until you get valid input. When you do know the iteration count or you're counting through indexes, a for loop is usually the clearer choice; while is for the open-ended cases.
Syntax
while (condition) {
// runs while condition is true
}
// runs the body at least once
do {
// ...
} while (condition);
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
let n = 1;
const powers = [];
// double until we pass 100
while (n <= 100) {
powers.push(n);
n *= 2;
}
document.getElementById('out').textContent = powers.join(', '); // 1, 2, 4, ... 64
</script>
Best practices
- Make sure the body changes something that will eventually end the loop, to avoid an infinite loop.
- Use
whilefor open-ended repetition; use a for loop when you know the count. - Reach for
do...whilewhen the body must run at least once. - Use
breakfor an early exit andcontinueto skip to the next check.
Frequently asked questions
What is the difference between while and for?
while just takes a condition, suiting open-ended loops.What is an infinite loop and how do I avoid it?
What is the difference between while and do...while?
while checks the condition before the body, so it may run zero times; do...while checks after, so the body always runs at least once.How do I stop a while loop?
break to exit immediately.