Easy Tutorial
❮ Prop Text Disabled Event Metakey ❯

JavaScript do/while Statement

JavaScript Statement Reference Manual

Example

The loop will execute at least once, even if the condition is false, because the code block is executed before the condition is checked:

var text = "";
var i = 0;
do {
    text += "<br>Number is " + i;
    i++;
} while (i < 5);
document.getElementById("demo").innerHTML = text;

text output result:

Number is 0
Number is 1
Number is 2
Number is 3
Number is 4

Definition and Usage

The do/while loop is a variant of the while loop. This loop 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.

JavaScript supports different types of loops:


Browser Support

Statement Chrome Edge Firefox Safari Opera
do/while Yes Yes Yes Yes Yes

Syntax

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

Parameter Values

Parameter Description
condition Required. Defines the condition for executing the loop. If it returns true, the loop will execute again; if it returns false, the loop ends. <br><br> Note: If the condition remains true, the loop will not end (infinite loop), which can crash your browser. <br><br> Note: If you use a variable as the condition, initialize the variable before the loop starts and increment it within the loop. If you forget to increment the variable, an infinite loop will occur, and your browser will crash.

Technical Details

| JavaScript Version: | 1.2 | | --- | --- |


Related Pages

JavaScript Tutorial: JavaScript While Loop

JavaScript Reference Manual: JavaScript while Statement

JavaScript Reference Manual: JavaScript for Statement


❮ Prop Text Disabled Event Metakey ❯