Loop Until a Condition Is False
JavaScript while
`while` runs while a condition is true. Reach for it when you don't know how many iterations you'll need.
What you'll learn
- Write a `while` loop
- Choose between `while` and `do..while`
- Avoid infinite loops
while keeps running its body for as long as the condition is true.
Unlike for, there’s no counter built into the syntax — you manage
the state yourself.
let i = 0;
while (i < 3) {
console.log(i);
i++;
}
// 0, 1, 2 This is equivalent to for (let i = 0; i < 3; i++) { … }. Use
while when “until something happens” reads better than counting.
let dice;
let rolls = 0;
while (dice !== 6) {
dice = Math.floor(Math.random() * 6) + 1;
rolls++;
}
console.log(`Got a 6 after ${rolls} rolls`); do..while — Run At Least Once
do..while checks the condition AFTER the body. The body runs at
least once.
let n = 10;
do {
console.log(n);
n--;
} while (n > 0);
// 10, 9, 8, ..., 1 do..while is rare — useful when “we want to ask the user at least
once” patterns. For most loops, plain while is fine.
Avoiding Infinite Loops
A while loop forgets the condition is your responsibility. If
nothing inside the body ever makes the condition false, you have an
infinite loop.
let n = 0;
while (n < 10) {
console.log(n);
// Forgot n++ — n stays at 0 forever
} If your tab freezes, this pattern is the usual culprit. Modern browsers will eventually offer to kill the page, but you’ll lose unsaved state.
When to Use Each Loop
| Loop | Reach for it when… |
|---|---|
for | Iterating a fixed count or numeric range |
for..of | Iterating values in an array, string, set, map |
for..in | Iterating an object’s keys |
while | Looping until a condition becomes false |
do..while | Same, but the body must run at least once |
forEach | Side-effect-y iteration, no break needed |
map/filter/reduce | Building a new array or value from existing items |
Up Next
Two keywords that change the flow inside any loop — break and
continue.