do…while statement

The do...while statement creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.

Syntax

do {
  code block to be executed
}
while (condition);

Parameters

Parameter

Description

condition

Required. The condition for running the code block. If true, the loop will start over again, otherwise it ends.

Examples

In the following example, the do...while loop iterates at least once and reiterates until i is no longer less than 5.

let result = "";
let i = 0;
do {
  i += 1;
  result += `${i} `;
} while (i > 0 && i < 5);
// Despite i === 0 this will still loop as it starts off without the test

console.log(result);

Copy to Clipboard

In some cases, it can make sense to use an assignment as a condition — but when you do, there's a right way to do it, and a wrong way; the while documentation has a Using an assignment as a condition section with an example showing a general best-practice syntax you should know about and follow.

The do...while loop

One often-overlooked variation of the while loop, with a sligtly different syntax, is the do...while loop. It serves a crucial purpose that the typical while doesn't.

That is,

do...while first evaluates the loop's body and then checks the condition (for the next iteration).

Hence, when the given condition is false to begin with, do...while still executes the body once.

First, let's see the syntax of do...while:

do statement;
while (condition);

As before, statement is the loop's body whereas condition is the iteration condition.

It's invalid to put two semicolons (;) at the end of the do statement. That's because after the first semicolon (which is optional), the do statement ends, and likewise a while is expected before the second semicolon. Putting two semicolons one after another simply misses out the while statement, and this is the reason why doing so is syntactically invalid.

Now you might ask what's the benefit of this approach?

Well, sometimes we do want to execute a certain piece of code and only after that check for some condition, before executing the code again.

A common example would be obtaining an input again and again till the entered value is valid.

Consider the following code:

do {
   var input = prompt('Enter a number');
}
while (isNaN(Number(input)));

alert(`You entered the number ${input}`);

Live Example

First we have the do block with one statement, asking for the user's input which must be a valid number. Next, in the while part of the loop, we check whether the value input coerces to NaN. If it does, this means that the provided input was some arbitrary value not able to be coerced into a number, and so likewise we must repeat the prompt.

In words, we can read the code above as "keep asking for the user's input while the entered value is NaN."

Such a loop that runs until an entered value is valid is often referred to as an input-validation loop.

Note that the code above can be rewritten using a plain while loop as well. Below shown is an illustration:

var input = prompt('Enter a number');

while (isNaN(Number(input))) {
   input = prompt('Enter a number');
}

alert(`You entered the number ${input}`);

Notice that we have to repeat the loop's body before the actual while statement. This is so that input can be set to a particular value before executing the loop, asking the user to input again.

One obvious way out of this repetition is to predefine the variable input with a dummy value (undefined will also work in this case) that'll get at least the first iteration of the loop to execute.

For instance, we can set input to NaN ourself, and thus get the loop's condition to be met, thereby leading to the execution of the input prompt, after which input will be evaluated once again for the next iteration.

// Set to NaN in order to execute the following loop at least once.
var input = NaN;

while (isNaN(Number(input))) {
   input = prompt('Enter a number');
}

alert(`You entered the number ${input}`);

This technique surely works, but it's not really that intuitive.

Ideally, we should use do...while for such a scenario since it was made purposefully for such a scenario. Moreover, with this approach, we have to predeclare the variables involved in the loop's condition before the while statement.

This doesn't have to be done with a do...while loop — the respective variables can be defined right inside the do block and then remain accessible in the while clause.

To boil it down, whenever we wish to execute a piece of code repeatedly but check the condition after the code (not before it), we must use a do...while loop. It might be an occasional programming construct but when used, is extremely versatile and elegant.

Last updated