JavaScript While Loop
The while loop repeats a block of code while its condition stays true. The condition is checked before every turn of the loop.
Counting with while
This loop counts from 1 to 5. The step sits inside the body, unlike the for loop header.
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}Running once with do...while
The condition starts false here. The body still runs one time before the first check.
let count = 10;
do {
console.log(count);
count++;
} while (count < 5);Stopping on a condition
The loop runs while fuel remains. The last line runs after the loop ends.
let fuel = 3;
while (fuel > 0) {
console.log("Fuel left:", fuel);
fuel--;
}
console.log("Empty");Example
let value = 3;
while (value < 100) {
value = value * 2;
}
console.log(value);Key points
- The step lives inside the body, not in a header.
- The body may run zero times when the condition starts false.
- do...while checks its condition after the body runs.
- A do...while body always runs at least once.
In this example, the value starts at 3. Each turn doubles the value. The loop stops once the value reaches 100 or more. The log shows 192, the first doubled value past 100.
Note
A condition that never changes makes the loop run forever.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What happens if a while loop condition never turns false?