Simple example of While and Do While loop in JavaScript

If you want to run same code many times, you can use concept of looping in JavaScript. In JavaScript, there are three types of loop statements are available: for, while and do... while.

While loop in JavaScript

while loop in JavaScript executes code while a condition is true. You can use While loop like as:


while (condition)
{
statement1;
statement2;
...
}

For example, you can make a program in JavaScript for displaying the list of numbers while the number is less than or equal to 10.

<html>
  <body>
    <script type="text/javascript">
	var number=0;
	while (number<=10)
 	 {
 	  document.write("The number is " + number);
  	  document.write("<br />");
 	  number++;
  	 }
    </script>
  </body>
</html>

In above example we defines a while loop that starts with 0 and this for loop will continue to run as long as number is less than or equal to 10. on here we will increase by 1 every time(see statement ‘number++’) the loop runs.

Output will be:

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

Do..While loop in JavaScript

There are many situation when we need to execute the loop at least one time and then check the condition. In this case you can use do while loop.

you can use Do While loop like as :

<html>
   <body>
       <script type="text/javascript">
           var number=0;
           do
            {
               document.write("The number is " + number);
               document.write("<br />");
               number++;
            }
          while (number<=4);
      </script>
   </body>
</html>

Webpage will show this output:

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4