Home Videos Exercises MCQ Q&A Quiz E-Store Services Blog Sign in Appointment Payment

JavaScript While loop

JavaScript includes while loop to execute code repeatedly till it satisfies a specified condition. Unlike for loop, while loop only requires condition expression.

Example of while loop:
var i =0;
while(i < 5)
{ console.log(i);
i++;
}

output:
0 1 2 3 4

Make sure condition expression is appropriate and include increment or decrement counter variables inside the while block to avoid infinite loop.

As you can see in the above example, while loop will execute the code block till i < 5 condition turns out to be false. Initialization statement for a counter variable must be specified before starting while loop and increment of counter must be inside while block.


do while

JavaScript includes another flavour of while loop, that is do-while loop. The do-while loop is similar to while loop the only difference is it evaluates condition expression after the execution of code block. So do-while loop will execute the code block at least once.

Example of do while loop:
var i = 0;
do{
alert(i);
i++;
} while(i< 5);

Output:
0 1 2 3 4

The following example shows that do-while loop will execute a code block even if the condition turns out to be false in the first iteration.

Example:
var i =0;
do{
alert(i);
i++;
}
while(i<1);

output:
0