In javascript a while loop will repeat as long as specified condition evaluates true. When a while loop is executed, it follows the below steps:-
while ([condition])
{
code statements
}
Below is a while loop which has the condition set to counter < 20. This will make the loop run as long as the variable counter is less than 20. While the condition evaluates to true, the loop will print out "Value is" followed by the value of counter.
The last statement (counter++;) increments the counter value by 1. This is done so that the loop condition eventually becomes false and not end up in an infinite loop. The below code will print out values 0 through 19. Once counter hits 20, the condition will evaluate to false and the loop will end.
var counter = 0;
while (counter < 20)
{
document.write("Value is " + counter + "<br>");
counter++;
}
Now if the counter was being incremented before we print the value (as seen in below example), then it will print values 1 thorough 20.
var counter = 0;
while (counter < 20)
{
counter++;
document.write("Value is " + counter + "<br>");
}
In below example, the variable counter is set to value of 20. When the code reaches the while loop, it will evaluate the condition and since value of counter is not less than 20; it will not execute the loop code statements.
var counter = 20;
while (counter < 20)
{
counter++;
document.write("Value is " + counter + "<br>");
}
In javascript a do .. while loop will repeat as long as specified condition evaluates true. Compared to while loop, the do..while loop will always execute the code statements at least once. When a do..while loop is executed it follows the below steps:-
do
{
code statements
}
while ([condition])
Below do..while example will print out doCount values from 0 to 19. Once doCount reaches 20, the condition evaluates to false and loop ends.
var doCount = 0;
do
{
document.write("Do value is " + doCount + "<br>");
doCount++;
}
while (doCount < 20)
Now if the doCount was being incremented before we print the value (as seen in below example), then it will print values 1 thorough 20.
var doCount = 0;
do
{
doCount++;
document.write("Do value is " + doCount + "<br>");
}
while (doCount < 20)
In below example, the variable doCount is set to value of 20. When the code reaches the while loop, it will execute the code statements; which increment doCount and then print its value. Then the do..while condition will be evaluated, at this point the doCount value is 21, and it evaluates false ending the loop.
var doCount = 20;
do
{
doCount++;
document.write("Do value is " + doCount + "<br>");
}
while (doCount < 20)