WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript While Loop


Loops can execute a square of code up to a predetermined condition is true.


The While Loop

The while circle circles through a square of code up to a predefined condition is true.

Syntax

while (condition) {
    code square to be executed
}

Example

In the accompanying model, the code tuned in will run, again and again, as long as a variable (I) is under 10:

Example

while (I < 10) {
    content += "The number is " + i;
    i++;
}
Try it yourself »

The Do/While Loop

The do/while circle is a variation of the while circle. This circle will execute the code square once, before checking on the off chance that the condition is valid, at that point it will rehash the circle as long as the condition is true.

Syntax

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

Example

The model underneath utilizations a do/while circle. The circle will dependably be executed at any rate once, regardless of whether the condition is false, in light of the fact that the code square is executed before the condition is tested:

Example

do {
    content += "The number is " + i;
    i++;
}
while (I < 10);
Try it yourself »

Do not neglect to expand the variable utilized in the condition, generally the circle will never end!


Comparing For and While

If you have perused the past part, about the for circle, you will find that some time circle is much equivalent to a for circle, with proclamation 1 and explanation 3 omitted.

The circle in this precedent uses a for loop to gather the vehicle names from the autos array:

Example

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

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

The circle in this precedent uses a while loop to gather the vehicle names from the autos array:

Example

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

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