Tutorials JavaScript while & do...while
Ch 20 / 78
Chapter 20 Beginner 6 min read JavaScript

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.

What you'll learn
while loop syntax — condition checked before body runs
do...while loop — body always runs at least once
How while differs from for and do...while
Preventing infinite loops safely
break and continue inside while loops
Real-world patterns — retry logic, input validation, polling

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:

for
Count-Controlled Loop
Init, condition, and update packed into one line. Best when the number of iterations is known before the loop starts.
Use when: iterating arrays, counting 1–n, stepping through indices.
while
Condition-First Loop
Checks the condition before each iteration. Body may never execute if the condition starts false.
Use when: iteration count is unknown — polling, retrying, reading streams.
do...while
Body-First Loop
Runs the body first, then checks the condition. Body always executes at least once, even if the condition is false.
Use when: at least one execution is required — menus, input prompts, first-run setup.

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.

while (condition) {
  // body — runs as long as condition is true
  update;  // ← must update something or loop runs forever
}
Condition — checked before every iteration Body — code that repeats while condition is true Update — must bring condition closer to false
while — execution order
1 Check condition — if false, skip to end
2 Run body — executes all statements
3 Go back to step 1 — re-evaluate condition
4 Exit loop when condition becomes false
do...while — execution order
1 Run body — always runs first, no check yet
2 Check condition — if false, exit; if true, continue
3 Run body again — back to step 1
4 Exit loop when condition becomes false
JavaScript — while Loop
// 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 ≥ 100
Watch out
Always ensure the loop body changes something that moves the condition toward false. 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:

do {
  // body — runs at least once, always
  update;
} while (condition);  // ← semicolon required!
Body — runs first, before any condition check Update — inside the body, moves toward exit Condition — checked after body; loop continues if true Semicolon — mandatory after the closing parenthesis
JavaScript — do...while Loop
// 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 given
Tip
The semicolon after while (...) 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
JavaScript — Same Result, Different Loop
// 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:

break
Immediately terminates the entire loop. Execution continues with the statement after the loop's closing brace.
continue (while)
Skips the rest of the current iteration body and jumps back to re-check the while (condition) at the top.
continue (do...while)
Skips the rest of the current body and jumps directly to the while (condition) check at the bottom.
JavaScript — break & continue
// ── 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:

Input Validation
Keep prompting the user until they enter valid data. Must run at least once to ask the first time.
do...while
Retry Logic
Retry a failing network request up to N times, stopping early if it succeeds.
while
Polling
Keep checking a queue, sensor, or API until a result becomes available.
while
Menu Systems
Show a menu, process the choice, then show again — until the user selects "Exit".
do...while
Unknown Sequence Length
Process items until a sentinel value (like -1 or null) is encountered.
while
Game Loops
Keep the game running while the player is alive; exit the loop when game-over condition is met.
while
⚡
Free Resource
Download our JavaScript Cheat Sheet
Loops, control flow & iteration patterns — all on one page.
Get Sheet

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.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

These are everyday while-loop utilities you'll use constantly in real JavaScript projects:

JavaScript — while Loop Recipes
// ── 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 1
Quick Check
How many times does a do...while loop run if the condition is false from the start?
Quick Check
Which punctuation mark is mandatory at the end of a do...while loop?
Chapter Summary
  • 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) in do...while — this is mandatory, not optional.
  • Always ensure the loop body modifies something that brings the condition toward false — or use break — 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.
  • break exits the loop; continue skips to the condition check in while, or to the bottom condition check in do...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

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel