While Loops in JavaScript
Introduction
while and do...while loops repeat code while a condition stays true. They fit situations where you do not know the exact iteration count upfront—reading input, polling status, or retrying network calls. This chapter contrasts them with for loops and shows safe patterns.
Prerequisites
while Loop
Checks the condition before each iteration:
// Count down from 3
let count = 3;
while (count > 0) {
console.log(count);
count -= 1;
}
console.log("Go");If the condition starts false, the body never runs.
do...while Loop
Runs the body at least once, then checks the condition:
// Ask at least once (simulated input)
let attempt = 0;
let success = false;
do {
attempt += 1;
console.log(`Attempt ${attempt}`);
success = attempt >= 3;
} while (!success);
console.log("Success on attempt", attempt);while vs for
Use while when | Use for when |
|---|---|
| Iterations depend on runtime state | Count is known or tied to length |
| Condition may stay true until external change | Walking arrays with clear bounds |
// while: process until queue empty (simulated)
const queue = ["job-a", "job-b", "job-c"];
while (queue.length > 0) {
const job = queue.shift();
console.log("Running", job);
}Warning
Ensure the loop condition eventually becomes false—otherwise you create an infinite loop that freezes the terminal or tab.
Sentinel Values
Use a special value to stop input loops (classic pattern):
// Simulated read until sentinel -1
const inputs = [4, 8, -1, 99];
let index = 0;
let sum = 0;
while (index < inputs.length && inputs[index] !== -1) {
sum += inputs[index];
index += 1;
}
console.log("Sum before sentinel:", sum);Busy Waiting (Avoid in Real Apps)
Spinning forever without pause wastes CPU:
// Bad pattern — do not run
// while (!ready) { }In production, use events, async/await, timers, or polling with delays.
Mini Example: Password Retry Limit
// Max 3 password attempts (simulated)
const correct = "s3cret";
const attempts = ["wrong", "nope", "s3cret"];
let i = 0;
let loggedIn = false;
while (i < 3 && !loggedIn) {
const guess = attempts[i] ?? "wrong";
if (guess === correct) {
loggedIn = true;
console.log("Login success");
} else {
console.log(`Attempt ${i + 1} failed`);
}
i += 1;
}
if (!loggedIn) {
console.log("Account locked");
}FAQ
Can I replace every for with while?
Often yes logically, but for communicates intent better when counting.
Is do...while common in modern JS?
Less common than while and for, but useful when you need one guaranteed run.
How do I break out of a while?
Use break, return, or set the condition variable to end the loop—see break and continue.
What comes next?
Break and continue, then objects.