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

while (Condition)
{
Code to be executed
}

Examples

The loop in this example will continue to run as long as the variable i is less than 5:

Examples

while (i<5) { x=x + "The number is " + i + "<br>"; i++; }

Try it Yourself »

lamp 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

do
{
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:

Examples

do { x=x + "The number is " + i + "<br>"; i++; } while (i<5);

Try it Yourself »

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

cars=["BMW","Volvo","Saab","Ford"]; var i=0; for (;cars[i];) { document.write(cars[i] + "<br>"); i++; }

Try it Yourself »

The loop in this example usesa while loopto display all the values in the cars array:

Examples

cars=["BMW","Volvo","Saab","Ford"]; var i=0; while (cars[i]) { document.write(cars[i] + "<br>"); i++; }

Try it Yourself »
Other Extensions