Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript do...while Loop

The do...while loop runs its body once before checking the condition.

This guarantees at least one iteration.

Why We Need It

Some tasks must run at least once, such as showing a menu or validating input.

do...while matches that pattern without extra boilerplate.

Syntax

do { ... } while (condition)

Basic Example

1. Basic do...while

let i = 0;

do {
  console.log(i);
  i++;
} while (i < 3);

The body runs before the condition check.

Real World Example

2. Run Once Even if False

let count = 0;

do {
  console.log("Runs once");
} while (count > 0);

Even though the condition is false, it runs once.

Multiple Use Cases

Run At Least Once

do...while runs the body first and checks the condition afterward.

Use it when the body must execute at least once.

Validation Loops

It is useful for input validation and menus that must show at least once.

The loop continues as long as the condition remains true.

Avoid Infinite Loops

Just like while, make sure the condition can become false.

Update counters or state inside the loop.

More Examples

3. Menu Loop

let choice = "";
let attempts = 0;

do {
  attempts++;
  choice = attempts === 2 ? "exit" : "stay";
} while (choice !== "exit");

console.log(choice);

Common for menu interactions and retries.

4. Validation Example

let value = -1;

do {
  value++;
} while (value < 0);

console.log(value);

Ensure a validation step happens at least once.

Comparison

Without

let i = 0;
console.log(i);
i++;
while (i < 1) {
  console.log(i);
  i++;
}

With

let i = 0;
do {
  console.log(i);
  i++;
} while (i < 1);

Common Mistakes and Fixes

Assuming the condition is checked first

Remember do...while checks after the body runs.

Forgetting to update the condition

Update counters or state to avoid infinite loops.

Using do...while unnecessarily

Use while if the body should not always run.

Interview Questions

When does do...while check the condition?

After running the body once.

When should you use do...while?

When you need the loop body to run at least once.

How do you avoid infinite loops?

Ensure the condition can become false.

Practice Problem

Practice: Use do...while to print numbers from 1 to 3.

let i = 1;
// TODO: print 1, 2, 3 using do...while

One Possible Solution

let i = 1;
do {
  console.log(i);
  i++;
} while (i <= 3);

Frequently Asked Questions

What is the difference between while and do...while?

do...while runs the body at least once before checking the condition.

When should I use do...while?

When you need the body to run at least once, like menus or input validation.

Can do...while be replaced by while?

Yes, but you would need an extra first run before the loop.

Try It Yourself

Try a do...while loop and change the condition to see the effect.