JavaScript do...while

Beginner
5 min read
Updated: Nov 2026
3 examples

Definition and Usage

do...while runs the body first, then checks the condition. Use it when you need at least one pass (menus, prompts, read-until-valid patterns).

JavaScript Syntax

JavaScript
let n = 0;
do {
  console.log(n);
  n++;
} while (n < 2);
Try it Editor

How It Works

  1. Body first. Prints 0 even before the check.
  2. Then check. Continues while n < 2.

Examples

Example 1 — Runs once when condition is false

Unlike while, the body still runs.

JavaScript
do {
  console.log("once");
} while (false);
Try it Editor

How It Works

  1. Body executes.
  2. Condition false → stop.

Example 2 — Retry pattern

Attempt, then decide whether to continue.

JavaScript
let tries = 0;
do {
  tries++;
  console.log("try " + tries);
} while (tries < 3);
Try it Editor

How It Works

  1. Increments tries each pass.
  2. Stops when tries reaches 3.

Example 3 — Prefer while when possible

If zero passes are OK, while is clearer.

JavaScript
console.log("use while when zero passes are fine");
Try it Editor

How It Works

  1. Choose the loop that matches your intent.

Frequently Asked Questions

When the body must run at least once before you know whether to continue.
Yes after the while (...); closing the do...while statement.

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful