WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript While Loop


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


The While Loop

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

Syntax

while (condition) {
    Code to execute
}

Example

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

Example

while (i < 10) {
    x=x + "The number is " + i + "<br>"
    i++;
}
Try it yourself »
If you forget to increase the value of the variable used in the condition, the loop never ends. This may cause the browser to crash.

The Do/While Loop

The do /while loop is a variant of the while loop. The loop executes a block of code before checking if the condition is true, and then repeats the loop if the condition is true.

Syntax

do {
    Code to execute
}
while (condition);

Example

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

Example

do {
    x = x "The number is " + i + "<br>";
    i++;
}
while (i < 10);
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 while loops are very similar to for loops.

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

Example

var car = ["BMW", "Hyundai.", "Mercedes-Benz", "Nissan"];
var I = 0;
var text = "";

for (;cars[i];) {
    text += cars[i] + "<br>";
    i++;
}
Try it Yourself »

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

Example

var vehicles = ["BMW", "Hyundai.", "Mercedes-Benz", "Nissan"];
var I = 0;
var text = "";

while (cars[i]) {
    text += cars[i] + "<br>";
    i++;
}
Try it Yourself »