JavaScript do/while Statement | Rookie Tutorial
The do/while statement creates a loop that executes the code block once, and then repeats the loop as long as the condition is true.
Syntax
do {
// code block to be executed
}
while (condition);
Note: The condition should be a Boolean expression. If it evaluates to true, the code block will be executed again. Each execution of the code block is called an iteration.
Parameters
| Parameter | Description |
|---|---|
| condition | Optional. Used to determine whether to continue the loop. If it evaluates to true, the loop continues; if false, the loop stops. Note: If you omit this condition, a break statement must be placed inside the loop. |
| statement | Optional. The code to be executed as long as condition is true. Can be multiple statements (enclosed in a code block). Note: Use the break statement to stop the loop before the condition evaluates to false. |
Example
Example 1
Loop through the code block once, then continue looping as long as the variable i is less than 5:
var text = "";
var i = 0;
do {
text += "Number is " + i;
i++;
}
while (i < 5);
Example 2
In this example, the do/while statement loops as long as i is less than 10.
var i = 0;
do {
document.write("The number is " + i);
document.write("<br>");
i++;
}
while (i < 10);
Example 3
Press the button below to test the above example:
Differences from while loop
while loop checks the condition first. If the condition is false, the code block will not be executed.
do/while loop executes the code block once, then checks the condition. If the condition is true, the loop repeats.
Example
Even if the condition is false, the code block in the do/while statement will be executed at least once:
do {
// code block to be executed
}
while (false);
Browser Support
| Statement | Chrome | IE | Firefox | Safari | Opera |
|---|---|---|---|---|---|
| do/while | Yes | Yes | Yes | Yes | Yes |
YouTip