JavaScript

This page explains how a do...while loop runs its body once before checking its condition.

Goal: use do...while when an action must happen at least once, while still controlling when repetition stops.

do...while

A do...while loop executes its block first, then checks the condition. If the condition is true, it repeats. Therefore, the block always runs at least once.

JavaScript

do {
  // code to run
} while (condition);

A counting example

JavaScript

let count = 0;

do {
  console.log(`Count: ${count}`);
  count += 1;
} while (count < 5);

The body prints 0 through 4. Even if the condition were false before the loop started, the first print would still happen.

When is it useful?

Related topics