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.

Structure of while loop

Following is the basic 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.
  • Then comes statements of code to be executed in the while loop.
  • Finally update_the_counter e.g. i++.

Javascript While example

Following is an example of using 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 below:

Experience this example online


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

The do while loop

The javascript’s do while loop is just like 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 js do while to learn more about it.

Structure of do while

The basic structure of do while 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 do while if condition is false at first

As mentioned, the do while will at least run the code inside the loop once, even the condition is false at first. For 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.

Also see Javascript array | Javascript for | Javascript foreach

Was this article helpful?

Related Articles

Leave A Comment?