JavaScript do/while statement
- Previous Page debugger
- Next Page for
- Go to the Previous Level JavaScript Statement Reference Manual
Definition and Usage
The do/while statement creates a loop that executes the code block once before checking if the condition is true, and then it will repeat the loop as long as the condition is true.
When you want to run the loop at least once, regardless of the circumstances, always use the do/while statement.
JavaScript supports different types of loops:
- for - Loop the code block multiple times
- for/in - Loop through the properties of an object
- for/of - Loop through the values of an iterable object
- while - Repeat the code block while the specified condition is true
- do/while - Execute the code block once and then repeat the loop if the specified condition is true
Example
This loop will always execute at least once, even if the condition is false, because the code block is executed before the condition is tested:
var text = ""; var i = 0; do { text += "The number is " + i; i++; } while (i < 5);
Syntax
do { code block to be executed } while (condition);
Parameter Value
Parameter | Description |
---|---|
condition |
Required. Defines the condition that runs the loop (code block). If it returns true, the loop will restart; if it returns false, the loop will end. Note:If the condition is always true, the loop will never end. This will cause your browser to crash. Note:If you use a variable with a condition, initialize it before the loop and increment it within the loop. If you forget to increase the variable, the loop will never end. This will also cause your browser to crash. |
Technical Details
JavaScript Version: | ECMAScript 1 |
---|
Browser Support
The numbers in the table specify the first browser version that fully supports this statement.
Statement | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
do/while | Support | 6.0 | Support | Support | Support |
Related Pages
JavaScript Tutorial:JavaScript While Loop
JavaScript Reference Manual:JavaScript while Statement
JavaScript Reference Manual:JavaScript for Statement
- Previous Page debugger
- Next Page for
- Go to the Previous Level JavaScript Statement Reference Manual