JavaScript While Loop


As long as the specified condition is true, the loop can always execute the code block.


while Loop

The while loop will loop through the code block when the specified condition is true.

Grammar

while (condition)
{
    code to be executed
}

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

Example

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

 Try It! 

lampIf you forget to increase the value of the variable is 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. The loop will execute the code block once before checking whether the condition is true, and then if the condition is true, the loop will be repeated.

Grammar

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

The following example uses a do/while loop. The loop will be executed at least once, even if the condition is false, it will be executed once, because the code block will be executed before the condition is tested:

Example

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

 Try It! 

Don't forget to increase the value of the variable used in the condition, otherwise the loop will never end!


Compare for Loop and while Loop

If you have read the content of the for loop in the previous chapter, you will find that the while loop is very similar to the for loop.

The loop in this example uses a for loop to display all the values in the cars array:

Example

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

 Try It! 

The loop in this example uses a while loop to display all the values in the cars array:

Example

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

 Try It!