JavaScript While loop

While loop in Javascript

JavaScript While loop

The JavaScript While loop repeats through a block of code, as long as a specified condition is true.JavaScript supports all the necessary loops to ease down the pressure of programming.

While writing a program, you may encounter a situation where you need to perform an action over and over again. In such situations, you would need to write loop statements to reduce the number of lines.


The JavaScript While loop

The while loop repeats through a block of code, as long as a specified condition is true.

If you forget to increase the variable used in the condition, the loop will never end.


Flow Chart


Example

Try the following example to implement while loop.

<html>

   <body>

      

      <script type = "text/javascript">

         <!--

            var count = 0;

            document.write("Starting Loop ");

         

            while (count < 10) {

               document.write("Current Count : " + count + "<br />");

               count++;

            }

         

            document.write("Loop stopped!");

         //-->

      </script>

      

      <p>Set the variable to different value and then try...</p>

   </body>

</html>

The do…while Loop

The do…while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, and then it will repeat the loop as long as the condition is true.


Example

Try the following example to learn how to implement a do-while loop in Java Script.

<html>

   <body>   

      <script type = "text/javascript">

         <!--

            var count = 0;

            

            document.write("Starting Loop" + "<br />");

            do {

               document.write("Current Count : " + count + "<br />");

               count++;

            }

            

            while (count < 5);

            document.write ("Loop stopped!");

         //-->

      </script>      

      <p>Set the variable to different value and then try...</p>

   </body>

</html>

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *