JavaScript do...while Loop

Subject: JavaScript

The do...while loop in JavaScript is used when you want to execute a block of code at least once, and then repeat it as long as a condition is true. Unlike a regular while loop, the do block runs before checking the condition.


Syntax

  • The code block runs once initially.
  • The condition is evaluated after the first iteration.

Example 1: Basic do...while Loop


Example 2: Run At Least Once

Even though the condition was initially false, the block still ran once.


Example 3: With continue and break


When to Use do...while

  • When you want to guarantee at least one execution.
  • For user prompts, input validation, or retry mechanisms.
  • When loop logic and validation are tightly coupled.

Key Takeaways

  • do...while always runs the loop at least once.
  • The condition is checked after running the code block.
  • Best for logic that must execute once, regardless of condition.
  • Use break to exit early and continue to skip iterations.
  • Make sure the condition eventually becomes false to avoid infinite loops.
Next : For In Loop