Easy Tutorial
❮ Js Obj Math Js Window ❯

JavaScript while Loop


As long as the specified condition is true, the loop will continue to execute the code block.


while Loop

The while loop will repeatedly execute the code block as long as the specified condition is true.

Syntax

Example

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++;
}

| | If you forget to increment the value of the variable used in the condition, the loop will never end. This can 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 if the condition is true, and then it will repeat the loop as long as the condition is true.

Syntax

Example

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

Example

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

Don't forget to increment 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 on for loops, you will find that while loops are very similar to for loops.

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

Example

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

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

Example

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