"do...while" Statement

Now we'll look at the syntax for the "do...while" statement. We discussed the "while" statement in a previous section. How do these statements differ? The "do...while" statement is executed until the test condition is false. 

Remember, when using the "do...while" statement, you must always use brackets in a "do...while" statement, and the body of the loop will always be executed at least once.

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.

let result = '';
let i = 0;

do {
  i = i + 1;
  result = result + i;
} while (i < 5);

console.log(result);
// expected result: "12345"


Syntax

do
   statement
while (condition);

statement

A statement that is executed at least once and is re-executed each time the condition evaluates to true. To execute multiple statements within the loop, use a block statement ({ ... }) to group those statements.

condition

An expression evaluated after each pass through the loop. If condition evaluates to true, the statement is re-executed. When condition evaluates to false, control passes to the statement following the do...while.


Example of using do...while

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

var result = '';
var 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);


Source: Charles W. Kann III, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while
Creative Commons License This work is licensed under a Creative Commons Attribution 4.0 License.

Last modified: Tuesday, October 4, 2022, 5:03 PM