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.

JavaScriptbeginner
9 min read

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

javascriptjavascript
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.

javascriptjavascript
let count = 0;
 
do {
  console.log(`Count: ${count}`);
  count++;
} while (count < 5);
 
// Count: 0
// Count: 1
// Count: 2
// Count: 3
// Count: 4

Execution Flow

StepActioncountCondition
1Run body0 -> 1Not checked yet
2Check 1 < 51true, continue
3Run body1 -> 2Not checked yet
4Check 2 < 52true, continue
............
9Run body4 -> 5Not checked yet
10Check 5 < 55false, exit

Do-While vs While: The Key Difference

The critical difference is when the condition is checked:

javascriptjavascript
// 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);
Featurewhiledo...while
Condition checkBefore each iterationAfter each iteration
Minimum executions01
Semicolon after conditionNoYes (required)
Common useUnknown iteration counts"At least once" patterns
When condition starts falseBody never runsBody 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:

javascriptjavascript
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:

javascriptjavascript
// 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

javascriptjavascript
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:

javascriptjavascript
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

javascriptjavascript
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

javascriptjavascript
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 usedIds

You 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

javascriptjavascript
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

javascriptjavascript
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

javascriptjavascript
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.4142156862745099

Integer to Binary Conversion

javascriptjavascript
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

javascriptjavascript
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));  // 5

Using 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

javascriptjavascript
// 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

javascriptjavascript
// 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

ScenarioBest loopWhy
Known iteration countforCounter management in one line
Array/iterable valuesfor...ofClean value access
Unknown count, may be zerowhileSkips entirely if condition is false
Must run at least oncedo...whileBody executes before condition check
Input validation promptdo...whileNeed input before validation
Menu display loopdo...whileMenu shows before choice check
Retry with limitdo...whileFirst attempt is unconditional
Processing until emptywhileMay 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

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
RunePowered by Rune AI

Frequently Asked Questions

When should I use do-while instead of while?

Use do-while when the loop body must execute at least once before the condition can be meaningfully evaluated. The classic examples are input validation (you need input before you can validate it), menu systems (the menu must display before the user can choose), and retry patterns (you must attempt the operation before deciding whether to retry). If the condition might be false from the start and you want to skip the body entirely, use while instead.

Can I use break and continue in a do-while loop?

Yes. The `break` statement exits the do-while loop immediately, skipping the condition check. The `continue` statement skips the rest of the current iteration and jumps directly to the condition check at the bottom. Both work the same way they do in while and for loops.

Is the semicolon after do-while required?

Yes. The syntax is `do { ... } while (condition);` with a semicolon at the end. Unlike a regular while loop (which ends with a closing brace), the do-while condition needs a semicolon to terminate the statement. Omitting it can cause issues with automatic semicolon insertion if the next line starts with certain characters.

Is do-while slower than while or for?

No. Modern [JavaScript engine](/tutorials/programming-languages/javascript/what-is-a-javascript-engine-a-complete-guide)s optimize all loop types to nearly identical performance. The choice between do-while, while, and for should be based entirely on readability and intent, not speed. The only performance consideration is the loop body itself, not the loop mechanism.

Can a do-while loop be infinite?

Yes. If the condition is always true and there is no `break` statement, a do-while loop runs forever. The same prevention strategies apply as with while loops: always ensure the body changes something that eventually makes the condition false, and add maximum iteration counters for loops driven by external data.

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.