while
Repeats a block of code while a condition remains truthy.
Syntax
while (condition) {
// ...
}
Examples
let i = 0;
while (i < 3) {
console.log(i);
i++;
}
Output
0
1
2
let n = 16;
let steps = 0;
while (n > 1) {
n = n / 2;
steps++;
}
console.log(steps);
Output
4
let x = 5;
while (x > 0) {
if (x === 3) break;
x--;
}
console.log(x);
Output
3
Notes
- The condition is checked before each iteration; if it is falsy at the
start the body never runs.
- Use `do...while` when the body must run at least once.
- Ensure the condition eventually becomes falsy to avoid an infinite
loop.
Browser & runtime support
| Environment | Since version |
|---|---|
| chrome | 1.0 |
| firefox | 1.0 |
| safari | 1.0 |
| edge | 12 |
| node | 0.10 |