JavaScript while Loop
As long as the specified condition is true, the loop can continue to execute the code block.
while Loop
The while loop executes the code block repeatedly while the specified condition is true.
Syntax
{
Code to be executed
}
Examples
The loop in this example will continue to run as long as the variable i is less than 5:
| If you forget to increase the value of the variable used in the condition, the loop will never end. This may cause the browser to crash. |
do/while Loop
The do/while loop is a variant of the while loop. This loop will execute the code block once before checking whether the condition is true, and then it will repeat the loop if the condition is true.
Syntax
{
Code to be executed
}
while (Condition);
Examples
The following example uses a do/while loop. The loop will be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:
Don't forget to increase the value of the variable used in the condition, otherwise the loop will never end!
Comparing for and while
If you have read the previous chapter about for loops, you will find that the while loop is very similar to the for loop.
The loop in this example usesa for loopto display all the values in the cars array:
Examples
Try it Yourself »
The loop in this example usesa while loopto display all the values in the cars array:
Examples
Try it Yourself »