JS Do-While Loop: Syntax and Practical Use Cases
Master the JavaScript do-while loop with practical examples. Learn the syntax, how it differs from while loops, when to use it for input validation, menus, retry logic, and game loops.
The while loop checks its condition before every iteration, which means the loop body might never run at all. But some tasks require at least one execution before the condition can even be evaluated. You cannot validate user input before you have received it. You cannot check if a network request succeeded before you have sent it. You cannot display a menu and ask for a choice before showing the menu at least once.
The do...while loop solves this by running the body first, then checking the condition. This "execute first, ask questions later" behavior makes it the right tool for input validation, menu systems, retry patterns, and any scenario where the first iteration is mandatory.
Do-While Syntax
do {
// code to repeat (runs at least once)
} while (condition);Note the semicolon after the closing parenthesis. This is one of the few places in JavaScript where a semicolon follows a closing brace.
let count = 0;
do {
console.log(`Count: ${count}`);
count++;
} while (count < 5);
// Count: 0
// Count: 1
// Count: 2
// Count: 3
// Count: 4Execution Flow
| Step | Action | count | Condition |
|---|---|---|---|
| 1 | Run body | 0 -> 1 | Not checked yet |
| 2 | Check 1 < 5 | 1 | true, continue |
| 3 | Run body | 1 -> 2 | Not checked yet |
| 4 | Check 2 < 5 | 2 | true, continue |
| ... | ... | ... | ... |
| 9 | Run body | 4 -> 5 | Not checked yet |
| 10 | Check 5 < 5 | 5 | false, exit |
Do-While vs While: The Key Difference
The critical difference is when the condition is checked:
// while: condition checked FIRST
let x = 10;
while (x < 5) {
console.log("while:", x); // never runs
x++;
}
// do-while: body runs FIRST, then condition checked
let y = 10;
do {
console.log("do-while:", y); // runs once, prints 10
y++;
} while (y < 5);| Feature | while | do...while |
|---|---|---|
| Condition check | Before each iteration | After each iteration |
| Minimum executions | 0 | 1 |
| Semicolon after condition | No | Yes (required) |
| Common use | Unknown iteration counts | "At least once" patterns |
| When condition starts false | Body never runs | Body runs exactly once |
When the Minimum Matters
If the starting condition is always true (like processing a non-empty queue), while and do-while behave identically. The do-while loop only differs when the condition might be false from the start, and you still need the first execution. Choose based on whether "at least once" is a requirement.
Practical Use Case 1: Input Validation
The most common use case. You need to get input before you can check if it is valid:
function getValidNumber(min, max) {
let input;
do {
input = parseInt(prompt(`Enter a number between ${min} and ${max}:`), 10);
if (isNaN(input) || input < min || input > max) {
console.log("Invalid input. Please try again.");
}
} while (isNaN(input) || input < min || input > max);
return input;
}
const age = getValidNumber(1, 120);
console.log(`Your age: ${age}`);With a regular while loop, you would need to duplicate the prompt or use a flag variable:
// while version: requires initialization trick
let input = NaN; // force first iteration
while (isNaN(input) || input < 1 || input > 120) {
input = parseInt(prompt("Enter a number between 1 and 120:"), 10);
}The do-while version reads more naturally: "Get input, then check if it is valid."
Practical Use Case 2: Menu Systems
function runMenu() {
let choice;
do {
console.log("\n=== Task Manager ===");
console.log("1. Add task");
console.log("2. View tasks");
console.log("3. Complete task");
console.log("4. Exit");
choice = prompt("Choose an option (1-4):");
switch (choice) {
case "1":
addTask();
break;
case "2":
viewTasks();
break;
case "3":
completeTask();
break;
case "4":
console.log("Goodbye!");
break;
default:
console.log("Invalid option. Please choose 1-4.");
}
} while (choice !== "4");
}The menu must display at least once. The user's choice determines whether to show it again. This is a natural fit for do-while.
Practical Use Case 3: Retry with Backoff
Retrying a network request until it succeeds or the retry limit is reached:
async function fetchWithRetry(url, maxRetries = 3) {
let attempt = 0;
let lastError;
do {
try {
const response = await fetch(url);
if (response.ok) {
return await response.json();
}
throw new Error(`HTTP ${response.status}`);
} catch (error) {
lastError = error;
attempt++;
console.log(`Attempt ${attempt} failed: ${error.message}`);
if (attempt < maxRetries) {
const delay = 1000 * Math.pow(2, attempt - 1);
await new Promise((r) => setTimeout(r, delay));
}
}
} while (attempt < maxRetries);
throw new Error(`Failed after ${maxRetries} attempts: ${lastError.message}`);
}You must make at least one request before deciding whether to retry. The do-while loop makes the first attempt unconditional.
Practical Use Case 4: Game Loop
function playGuessGame() {
const target = Math.floor(Math.random() * 100) + 1;
let guess;
let attempts = 0;
console.log("I'm thinking of a number between 1 and 100.");
do {
guess = parseInt(prompt("Your guess:"), 10);
attempts++;
if (isNaN(guess)) {
console.log("Please enter a valid number.");
} else if (guess < target) {
console.log("Too low!");
} else if (guess > target) {
console.log("Too high!");
} else {
console.log(`Correct! You got it in ${attempts} attempts.`);
}
} while (guess !== target);
}Practical Use Case 5: Generating Unique IDs
function generateUniqueId(existingIds) {
let id;
do {
id = Math.random().toString(36).substring(2, 10);
} while (existingIds.has(id));
return id;
}
const usedIds = new Set(["abc12345", "xyz98765"]);
const newId = generateUniqueId(usedIds);
console.log(newId); // a random 8-char string not in usedIdsYou must generate at least one ID before you can check for collisions. If the generated ID is unique (which it almost always is), the loop exits after one iteration.
Do-While with Break and Continue
Break for Alternative Exit Conditions
const MAX_ATTEMPTS = 10;
let attempt = 0;
do {
attempt++;
const result = performOperation();
if (result.criticalError) {
console.log("Critical error, stopping immediately.");
break; // exit regardless of attempt count
}
if (result.success) {
console.log(`Succeeded on attempt ${attempt}`);
break; // exit on success
}
console.log(`Attempt ${attempt} failed, retrying...`);
} while (attempt < MAX_ATTEMPTS);Continue for Skipping Invalid Iterations
do {
const input = getNextInput();
if (input === null) continue; // skip null inputs
if (input.trim() === "") continue; // skip empty strings
processValidInput(input);
} while (hasMoreInput());Continue in Do-While
When using continue in a do-while loop, execution jumps to the condition check, not to the top of the loop body. Make sure the condition still evaluates correctly after a continue. Unlike while loops, there is no risk of skipping the counter update since the condition is checked after the body.
Mathematical Algorithms with Do-While
Newton's Method for Square Root
function sqrt(n, precision = 0.0001) {
let guess = n / 2;
do {
guess = (guess + n / guess) / 2;
} while (Math.abs(guess * guess - n) > precision);
return guess;
}
console.log(sqrt(25)); // 5.000000000016778
console.log(sqrt(2)); // 1.4142156862745099Integer to Binary Conversion
function toBinary(n) {
if (n === 0) return "0";
let binary = "";
let num = Math.abs(n);
do {
binary = (num % 2) + binary;
num = Math.floor(num / 2);
} while (num > 0);
return n < 0 ? `-${binary}` : binary;
}
console.log(toBinary(10)); // "1010"
console.log(toBinary(255)); // "11111111"
console.log(toBinary(0)); // "0"Digit Counter
function countDigits(n) {
let count = 0;
let num = Math.abs(n);
do {
count++;
num = Math.floor(num / 10);
} while (num > 0);
return count;
}
console.log(countDigits(0)); // 1
console.log(countDigits(42)); // 2
console.log(countDigits(12345)); // 5Using a while loop here would incorrectly return 0 for the input 0, since 0 > 0 is false. The do-while correctly counts at least one digit.
Do-While Anti-Patterns
Using Do-While When While Is Clearer
// UNNECESSARY: the condition is always true on first check
const items = [1, 2, 3, 4, 5];
let i = 0;
do {
console.log(items[i]);
i++;
} while (i < items.length);
// BETTER: use a for loop for known-length iteration
for (let i = 0; i < items.length; i++) {
console.log(items[i]);
}Forgetting the Semicolon
// BUG: missing semicolon after while condition
do {
processItem();
} while (hasMore()) // <-- missing semicolon
// This can cause unexpected behavior when the next line
// starts with a parenthesis or bracket (ASI edge case)
// FIX: always include the semicolon
do {
processItem();
} while (hasMore());When to Use Each Loop Type
| Scenario | Best loop | Why |
|---|---|---|
| Known iteration count | for | Counter management in one line |
| Array/iterable values | for...of | Clean value access |
| Unknown count, may be zero | while | Skips entirely if condition is false |
| Must run at least once | do...while | Body executes before condition check |
| Input validation prompt | do...while | Need input before validation |
| Menu display loop | do...while | Menu shows before choice check |
| Retry with limit | do...while | First attempt is unconditional |
| Processing until empty | while | May start empty |
Best Practices
Use do-while only when the first iteration is mandatory. If a regular while or for loop works, prefer it. Do-while adds cognitive overhead because readers must scroll past the body to find the condition. Reserve it for genuine "at least once" requirements.
Keep the loop body focused. Since the condition is at the bottom, long bodies make it hard to understand when the loop exits. If the body exceeds 15-20 lines, extract logic into named functions.
Always include the trailing semicolon. The semicolon after while (condition); is required syntax, not optional. Missing it can trigger subtle automatic semicolon insertion issues with the next statement.
Prefer do-while over flag-variable hacks. If you find yourself writing let firstRun = true; while (firstRun || condition), a do-while is cleaner and communicates intent directly.
Add safety guards for unbounded conditions. Just like while loops, do-while loops can run infinitely. Include a maximum iteration counter when the condition depends on external data.
Next Steps
Master break and [continue statement](/tutorials/programming-languages/javascript/javascript-continue-statement-skipping-iterations)s
Learn how break exits loops early and continue skips iterations, giving you fine-grained control over loop flow in all loop types.
Explore [nested loop](/tutorials/programming-languages/javascript/how-to-write-nested-loops-in-javascript-tutorial) patterns
Combine do-while with for loops and while loops for complex iteration patterns like multi-level menus and grid processing.
Learn [array iteration](/tutorials/programming-languages/javascript/how-to-loop-through-arrays-using-js-for-loops-guide) methods
Discover .forEach(), .map(), .filter(), and .reduce() as declarative alternatives to manual loops for array processing.
Build practical projects with loops
Apply loops to real-world tasks: building a CLI calculator, processing CSV data, implementing a pagination system.
Rune AI
Key Insights
- Body runs first, condition checks second: the do-while loop guarantees at least one execution regardless of the condition
- Use for "at least once" patterns: input validation, menus, retries, and ID generation are the classic use cases
- Semicolon is required:
do { ... } while (condition);needs the trailing semicolon - Prefer while or for when "at least once" is not needed: do-while adds cognitive overhead since the exit condition is at the bottom
- Same infinite loop rules apply: always ensure the condition variable changes and add safety guards for external data
Frequently Asked Questions
When should I use do-while instead of while?
Can I use break and continue in a do-while loop?
Is the semicolon after do-while required?
Is do-while slower than while or for?
Can a do-while loop be infinite?
Conclusion
The do-while loop guarantees at least one execution of the loop body before checking the exit condition. This makes it the right choice for input validation, menu systems, retry logic, and any pattern where the first iteration is mandatory. Outside of these "at least once" scenarios, prefer while or for loops for their more familiar condition-first structure. The semicolon after the condition is required syntax, and the same infinite loop safeguards apply as with any other loop type.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.