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.
Syntax:
while(condition expression)
{
/* code to be executed
till the specified condition is true */
}
Example: while loop
var i =0;
while(i < 5)
{
console.log(i);
i++;
}
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 loop:
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.
Syntax:
do{
//code to be executed
}while(condition expression)
Example: do-while loop
var i = 0;
do{
alert(i);
i++;
} while(i < 5)
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: do-while loop
var i =0;
do{
alert(i);
i++;
} while(i > 1)
Points to Remember :
- 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.