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.

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++;
}
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.

Syntax:
do{

    //code to be executed

}while(condition expression)
Example: 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: do-while loop
var i =0;

do{
    
    alert(i);
    i++;

} while(i > 1)

Output:

0
Points to Remember :
  1. JavaScript while loop & do-while loop execute the code block repeatedly till conditional expression returns true.
  2. do-while loop executes the code at least once even if condition returns false.
Want to check how much you know JavaScript?