JavaScript do while loop

The do while loop is a variant of the while loop. It is an exit condition looping structure. It will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

In this tutorial, you will learn how to use the JavaScript do...while statement to create a loop that executes a block until a condition is false.

The do…while loop is similar to the while loop except that the condition check happens at the end of the loop. 

The do...while is used when you want to run a code block at least one time.

Because the do...while loop evaluates expression after each iteration, it’s often referred to as a post-test loop.

Syntax

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

Note − Don’t miss the semicolon used at the end of the do…while loop.

The body of the loop is executed at first. Then the condition is evaluated.

If the condition evaluates to true, the body of the loop inside the do statement is executed again.

The condition is evaluated once again. If the condition evaluates to true, the body of the loop inside the do statement is executed again. This process continues until the condition evaluates to false. Then the loop stops.

Flowchart

JavaScript do while loop flowchart

Example

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript do while loop example</title>
</head>

<body>
    <h2>JavaScript Do While Loop</h2>

    <p id="demo"></p>

    <script>
        let text = ""
        let i = 0;

        do {
            text += "<br>The number is " + i;
            i++;
        }
        while (i < 10);

        document.getElementById("demo").innerHTML = text;
    </script>
</body>

</html>
JavaScript do while loop example output

do...while loop is similar to the while loop. The only difference is that in do…while loop, the body of loop is executed at least once.