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.
while(condition expression)/* code to be executed till the specified condition is true */
var i =0;
while(i < 5)
{
console.log(i);
i++;
}
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.
do//code to be executedwhile(condition expression)
var i = 0;
do{
alert(i);
i++;
} while(i < 5)
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.
var i =0;
do{
alert(i);
i++;
} while(i > 1)
0
- JavaScript while loop & do-while loop execute the code block repeatedly till conditional expression returns true.
- do-while loop executes the code at least once even if condition returns false.