while & do...while
When you don't know exactly how many times a loop should run,
while and do...while
are your tools. They repeat as long as a condition stays
true — making them perfect for
user input validation, polling, and event-driven patterns.
JavaScript's Three Loop Types
JavaScript has three primary loop constructs. The for loop is ideal when you know the iteration count. The while and do...while loops shine when the count is unknown and determined by a runtime condition:
The while Loop
A while loop evaluates its
condition before every iteration. If the condition is
false from the start, the body never runs at all.
The update step is your responsibility — it must be inside the body.
// body — runs as long as condition is true
update; // ← must update something or loop runs forever
}
// Basic while loop — count from 1 to 5
let i = 1;
while (i <= 5) {
console.log(i); // 1 2 3 4 5
i++; // ← update: moves i toward false condition
}
// Condition starts false — body never runs
let x = 10;
while (x < 5) {
console.log("this never prints");
}
// ↑ x is already 10, so x < 5 is false — 0 iterations
// Countdown timer
let countdown = 3;
while (countdown > 0) {
console.log(`${countdown}...`);
countdown--;
}
console.log("🚀 Launch!");
// 3... 2... 1... 🚀 Launch!
// Loop until condition is met (unknown iteration count)
let n = 1;
while (n < 100) {
n *= 2; // 1 → 2 → 4 → 8 → 16 → 32 → 64 → 128
}
console.log(n); // 128 — first power of 2 ≥ 100false. Forgetting the update expression creates an infinite loop
that freezes the browser tab and requires a force-refresh to recover.
The do...while Loop
A do...while loop places the
condition after the body. This guarantees the body executes
at least once — even if the condition is immediately false.
Note the mandatory semicolon after the closing parenthesis:
// body — runs at least once, always
update;
} while (condition); // ← semicolon required!
// Basic do...while
let i = 1;
do {
console.log(i); // 1 2 3 4 5
i++;
} while (i <= 5); // ← semicolon!
// KEY difference — body runs even if condition is IMMEDIATELY false
let x = 10;
do {
console.log("runs once!"); // ← always prints
x++;
} while (x < 5); // x = 10, so 10 < 5 is false → exits after 1 run
// User input validation pattern (simulated)
let input;
do {
input = prompt("Enter a number between 1 and 10:");
} while (input < 1 || input > 10 || isNaN(input));
// Keeps asking until valid input is givenwhile (...) in a
do...while is not optional — it terminates the statement.
Omitting it is a syntax error. This is the most common mistake beginners
make when first writing do...while loops.
while vs do...while vs for
Choosing the right loop depends on when you know the iteration count and whether the body must run at least once:
| Feature | for | while | do...while |
|---|---|---|---|
| Iteration count known? | Usually yes | Often no | Often no |
| Condition checked | Before body | Before body | After body |
| Min iterations | 0 (can skip) | 0 (can skip) | Always at least 1 |
| Init & update location | In the header (...) |
Outside / inside body | Outside / inside body |
| Best for | Array iteration, counters | Polling, retrying, streams | Input validation, menus |
| Readability | Compact, self-contained | Expressive for open-ended loops | Clear "run once then check" intent |
// All three print 1 → 2 → 3 → 4 → 5
// for
for (let i = 1; i <= 5; i++) console.log(i);
// while
let i = 1;
while (i <= 5) { console.log(i); i++; }
// do...while
let j = 1;
do { console.log(j); j++; } while (j <= 5);
// ── Critical difference: initial condition is false ──────────
let k = 10;
while (k < 5) console.log("while"); // never prints
do { console.log("do-while"); k++; } while (k < 5); // prints once
break & continue in while Loops
break and
continue work identically in
while and do...while
as they do in for loops. The only difference is
where the condition is re-evaluated after a continue:
while (condition) at the top.while (condition) check at the bottom.
// ── break — stop searching when found ───────────────────────
const haystack = [3, 7, 11, 2, 8];
let idx = 0;
while (idx < haystack.length) {
if (haystack[idx] === 11) {
console.log(`Found 11 at index ${idx}`); // Found 11 at index 2
break;
}
idx++;
}
// ── continue — skip negative numbers ────────────────────────
const nums = [4, -1, 7, -3, 5];
let sum = 0, pos = 0;
while (pos < nums.length) {
if (nums[pos] < 0) { pos++; continue; } // skip negatives
sum += nums[pos];
pos++;
}
console.log(sum); // 16 (4 + 7 + 5)
// ── Infinite loop with intentional break ─────────────────────
let attempt = 0;
while (true) { // deliberate infinite — relies on break to exit
attempt++;
if (attempt >= 3) {
console.log("Max attempts reached");
break;
}
console.log(`Attempt ${attempt}...`);
}Real-World Use Cases
These are the scenarios where while
and do...while are the natural choice over a
for loop:
Try It — Live Editor
Experiment with while and
do...while loops below. Try changing the starting
value or condition to see the difference when the condition starts as false.
Common Patterns & Recipes
These are everyday while-loop utilities you'll use constantly in real JavaScript projects:
// ── Retry with max attempts ──────────────────────────────────
async function fetchWithRetry(url, maxRetries = 3) {
let attempts = 0;
while (attempts < maxRetries) {
try {
const res = await fetch(url);
if (res.ok) return await res.json();
} catch (e) { attempts++; }
}
throw new Error("Max retries reached");
}
// ── Drain a queue ────────────────────────────────────────────
const queue = ["task1", "task2", "task3"];
while (queue.length > 0) {
const task = queue.shift(); // removes from front
console.log(`Processing: ${task}`);
}
// ── Read digits of a number ──────────────────────────────────
function digits(num) {
const result = [];
while (num > 0) {
result.unshift(num % 10); // last digit
num = Math.floor(num / 10);
}
return result;
}
digits(1234); // [1, 2, 3, 4]
// ── do...while: show-menu-then-ask pattern ───────────────────
let choice;
do {
const menu = `\n1. View items\n2. Add item\n3. Exit`;
choice = +prompt("Menu:" + menu);
if (choice === 1) viewItems();
else if (choice === 2) addItem();
} while (choice !== 3);
// ── Collatz conjecture (unknown iterations) ───────────────────
function collatz(n) {
let steps = 0;
while (n !== 1) {
n = (n % 2 === 0) ? n / 2 : 3 * n + 1;
steps++;
}
return steps;
}
console.log(collatz(27)); // 111 steps to reach 1do...while loop run if the condition is
false from the start?
do...while
loop?- The while loop checks its condition before each iteration — if the condition starts false, the body never runs (0 iterations).
- The do...while loop runs the body first, then checks the condition — guaranteeing at least one execution.
- Both loops require a semicolon after
while (condition)indo...while— this is mandatory, not optional. - Always ensure the loop body modifies something that brings the condition
toward
false— or usebreak— to prevent infinite loops. - Use while when the iteration count is unknown: polling, draining queues, retry logic, reading streams.
- Use do...while when the body must execute at least once: input validation, menus, first-run setup.
breakexits the loop;continueskips to the condition check inwhile, or to the bottom condition check indo...while.while (true) { ... break; }is a valid and common pattern for loops that determine their own exit condition inside the body.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.