JavaScript While Loop

JavaScript While Loop cover image
  1. Home
  2. JavaScript
  3. JavaScript While Loop

The JavaScript while loop is much simpler than the for loop. It consists of a condition and the statement block.

while (condition)
   {
   ...statements...
   }

As long as the condition evaluates to ‘true’, the program execution will continues to loop through the statements.

In the previous session, we had used the for loop to display digits 1 to 10 in an alert box. We’ll now employ the while loop to do the same thing.

var msg = "";
var x = 1;
while (x <= 10)
   {
   msg = msg + x + "\n";
   x++;
   }
alert(msg);

Click here to check the code

Note that the initialization statement (X = 1) has been placed before the loop. The condition lies between the parenthesis and the updation statement (x++) is present inside the statement block.
It’s a common error by beginners to forget the updation statement in which case the condition will never evaluate to ‘false’ and this will result in an infinite loop. To avoid such situations, my humble advice is to write the updation statement right after starting the statement block. You can then build the rest of the code in the statement block.

We can also employ the while loop to display the 12 times table as we had done with for.

var msg = "";
var x = 1;
var res = 0;
while (x <= 10)
   {
   res = 12 * x;
   msg = msg + "12 X " + x + " = " + res + "\n";
   x++;
   }
alert(msg);

Click here to check the code

If the condition in while evaluates to ‘false’ at the very beginning, the loop is skipped altogether and program execution starts at the statement immediately following the loop.

The do-while loop

You can consider the do-while loop as a modified version of the while loop. Here, the condition is placed at the end of the loop and hence, the loop is executed at least once.

var x = 20;
do
   {
   alert("The number is " + x);
   x++;
   }
while (x <= 10);

Click here to check the code

In the code above, the value of variable x is 20, hence the condition evaluates to ‘false’. However, the loop is executed once since the condition is presented at the end of the loop and not at the beginning.

JavaScript