/    /  Javascript-While loop

Javascript-While loop

 

JavaScript includes a while loop to executes the code repeatedly till it satisfies a specified condition. The while loop only requires the condition expression.

 

Syntax:

 

while(condition expression)
{
 /* code to be executed
 till the specified condition is true */
}

 

Example:

 

<!DOCTYPE html>
<html>
<body>
       <h1>Demo: while loop</h1>
       <p id="p0"></p>
       <p id="p1"></p>
       <p id="p2"></p>
       <p id="p3"></p>
       <p id="p4"></p>

       <script>
                var i =0;

                while(i < 5)
                {
                        document.getElementById("p" + i).innerHTML = i;
                        i++;

                }
  </script>
</body>
</html>

 

OUTPUT:

 

Demo: while loop

0

1

2

3

4

 

do while:

 

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

 

Syntax:

 

do{

  //code to be executed

}while(condition expression)

 

Example:

 

<!DOCTYPE html>
<html>
<body>
       <h1>Demo: do while loop</h1>
       <p id="p0"></p>
       <p id="p1"></p>
       <p id="p2"></p>
       <p id="p3"></p>
       <p id="p4"></p>

       <script>
               var i =0;

               do{

                   document.getElementById("p" + i).innerHTML = i;

                   i++;

           } while(i < 5)

  </script>
</body>
</html>

 

OUTPUT:

 

Demo: do while loop

0

1

2

3

4

 

  • In JavaScript, while loop and do-while loop executes the block of code repeatedly till conditional expression, returns true.
  • The do-while loop executes the code at least once even if the condition returns false.