while loops
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
while repeats
while (test) { ... }runs again and again, as long as the test staystrue.- It checks the test before each pass — so the body might run zero times.
let n = 1;
while (n <= 3) {
console.log(n); // → 1, then 2, then 3
n++;
}
Make progress every pass
- Something inside must move the test toward
false. - If nothing changes, the loop never stops — an infinite loop (the Stop button saves you).
let n = 1;
while (n < 50) {
n = n * 2; // 2, 4, 8, 16, 32, 64 — then stop
}
console.log(n); // → 64
Explore
Each pass doubles n
while re-checks its test each pass. n must change, or it runs forever.
Common mistakes
- Change the condition inside the loop, or it runs forever.
- A
whilechecks its condition first, so it may run zero times.
Now you try
- Use a
whileloop. - Press Check answer to test it.
let n = 3. Use a while loop to count down: log 3, 2, 1, one per line.
Click Run to see the output here.
let n = 1. While n is 16 or less, log n then double it. Output should be 1, 2, 4, 8, 16.
Click Run to see the output here.
Use a while loop to add up 1 to 4, then log the total (it is 10).
Click Run to see the output here.