JavaScript While and do while Loop with Examples

JavaScript While and do while Loop with Examples

The while loop

The While loop is a way to iterate a block of code for a number of times until given condition is true. As condition evaluates as false the control will be out of while loop to the next line of code.

How to use the JavaScript while loop?

Following is the general structure of JavaScript while loop:

while (condition){

 //Code to be executed;

update_the_counter

}

e.g.

while (i <= 10) {

alert(i);

i++;

}

Where:

  • While is followed by a condition in parenthesis. The condition may look like “i<=10″ etc.
  • After that comes the statements of code to be executed in the while loop.
  • Finally update_the_counter e.g. i++.

An example of the while loop 

Following is an example of using the while loop where we will declare a variable with an initial value of 1. The while loop of JavaScript will be executed till i’s value is less than or equal to 10. See example by clicking the link or image below:

JavaScript while loop

Experience this example online

As you can see, numbers are printed in HTML paragraph by using the while loop.

The do while loop

The JavasSript’s do while loop is just like the while loop except do while will at least execute the given statement once inside the loop. Whereas in JS while loop, if the condition is false at first turn the control will be out of the loop without executing any statement inside while loop.

The do while JavaScript becomes useful if you need to execute code inside the loop at least once. This happens as the condition is evaluated at the last part of the do-while loop. See structure and example of using the do while to learn more about it.

Structure of the do while

The basic structure of the do while lopp is:

do {

//Code to be executed;

update_the_counter;

}

While (condition)

Example of using JavaScript do while

Following is a simple example of using do while to display numbers from 1 to 10 by using a variable “i” and running do while loop.

Experience this example online

Example of the do while if condition is false at first

As mentioned earlier, the do while will at least run the code inside the loop once, even the condition is false at first.

To demonstrate that, we simply initiated variable value of i=11 whereas the condition is i<=10. See the example by clicking the link below:

Experience this example online

As you can see, the value of i is displayed in HTML paragraph, even the condition that it met return false.

Further Reading: JavaScript array | JavaScript for loop | The foreach loop