Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript do...while Loop

Learn do...while loops that guarantee at least one execution. Master post-condition loops in JavaScript.

Why this matters

do...while loops ensure your code runs at least once, making them perfect for menus, input validation, and initialization routines that need guaranteed execution.

What is a do...while Loop?

The do...while loop is similar to while loop, but with one crucial difference: it executes the code block first, then checks the condition.

This guarantees that the loop body will execute at least once, even if the condition is initially false.

Basic do...while Loop

let count = 0;

do {
  console.log("Count:", count);
  count++;
} while (count < 5);

// Output:
// Count: 0
// Count: 1
// Count: 2
// Count: 3
// Count: 4

The loop executes once before checking the condition, ensuring at least one iteration.

do...while vs while Loop

The key difference is when the condition is evaluated. do...while guarantees execution, while while might execute zero times.

Comparison: while vs do...while

let x = 10;

// while: might not execute
while (x < 10) {
  console.log("while: This won't print");
}

// do...while: executes at least once
do {
  console.log("do...while: This prints once");
} while (x < 10);

do...while executes the body first, then checks the condition.

Common Use Cases

do...while loops are perfect for scenarios where you need to perform an action before checking if it should continue.

Menu System

let choice;

do {
  console.log("Menu:");
  console.log("1. Play Game");
  console.log("2. View Scores");
  console.log("3. Exit");

  choice = getUserChoice(); // Get user input

  switch (choice) {
    case 1:
      startGame();
      break;
    case 2:
      showScores();
      break;
    case 3:
      console.log("Goodbye!");
      break;
    default:
      console.log("Invalid choice");
  }
} while (choice !== 3);

Display menu at least once, then continue based on user choice.

Input Validation

let userInput;

do {
  userInput = prompt("Enter a number between 1-10:");

  if (isNaN(userInput)) {
    console.log("That's not a number!");
  } else if (userInput < 1 || userInput > 10) {
    console.log("Number must be between 1 and 10!");
    userInput = null; // Reset to continue loop
  }
} while (!userInput);

console.log("Valid input:", userInput);

Always prompt for input at least once, then validate and repeat if necessary.

Game Loop

let gameState = {
  running: true,
  level: 1,
  score: 0
};

do {
  // Render game
  renderGame(gameState);

  // Process user input
  let action = getUserInput();

  // Update game state
  if (action === "quit") {
    gameState.running = false;
  } else {
    updateGameState(gameState, action);
  }

  // Check win/lose conditions
  if (gameState.score >= 100) {
    console.log("You win!");
    gameState.running = false;
  }

} while (gameState.running);

console.log("Game over!");

Game renders and processes input at least once before checking if it should continue.

Syntax and Structure

The do...while loop has a distinct structure where the condition comes after the code block.

do...while Structure

do {
  // code to execute
  // this runs at least once
} while (condition); // condition checked after execution

The semicolon after the while condition is required and easy to forget.

Best Practices

Use do...while when you need guaranteed execution. Otherwise, prefer while or for loops.

  • Use when you need at least one execution
  • Perfect for menu systems and input validation
  • Remember the semicolon after while condition
  • Keep loop body focused and readable
  • Ensure condition will eventually become false
  • Consider while loops for most other cases

Common Mistakes

  • Forgetting the semicolon: Always include the semicolon after the while(condition) statement.
  • Using do...while unnecessarily: Use do...while only when you need guaranteed execution. Prefer while for most cases.
  • Infinite loops: Ensure the condition will eventually become false.

Frequently Asked Questions

When should I use do...while instead of while?

Use do...while when you need the code to execute at least once, regardless of the initial condition.

Why is there a semicolon after do...while?

The semicolon is required syntax. It's easy to forget since most JavaScript statements don't need semicolons there.

Can do...while loops be nested?

Yes, like any other loop construct, do...while can be nested inside other loops or contain nested loops.