Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

JavaScript while loop


May 06, 2021 JavaScript


Table of contents


JavaScript while loop


The purpose of the JavaScript while loop is to execute statements or blocks of code over and over again.

Loops can execute blocks of code all the time as long as the specified condition is true.


While loop

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

Grammar

while ( condition )
{
Code that needs to be executed
}

Instance

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

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

Try it out . . .

Tip: In the JavaScript programming practice section of this site, you can do iterations using while statement loops with practice.

JavaScript while loop 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.


Do/while loop

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

Grammar

do
{
Code that needs to be executed
}
while ( condition );

Instance

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

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

Try it out . . .

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


Compare for and while

If you've read the previous chapter about for loops, you'll find that the while loop looks a lot like the for loop.

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

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

Try it out . . .

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

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

Try it out . . .