1. Tech

Your suggestion is on its way!

An email with a link to:


was emailed to:

Thanks for sharing About.com with others!

Learn Javascript

The WHILE Loop

Join the Discussion

Questions? Comments?

More of this Tutorial

The FOR Loop Quiz Yourself

Related Terms



Even easier to use than the for loop is the while loop. A while loop doesn't initialize or increment any fields automatically as part of the command, it just tests a condition and executes the loop for as long as the condition remains true.

Looping with While

Let's begin by looking at a simple while statement:

var x = 0;
while (x<10) {

The above example produces the numbers from 0 through 9 just as in the example in the last tutorial. The difference is that this time we need to initialize the variable before the start of the loop and increment the variable before the end of the loop.

A common error when using the while loop is to forget to do anything that might change the value being tested on while statement from within the loop. If the variable being tested is not changed within the loop then the condition will either never be true and the loop will therefore never get executed or it will always be true and will execute forever.

One trick some programmers use if the looping conditions are extremely complicated is to set the loop up so that it will loop forever and then code a number of if statements within the loop to test for when to terminate the loop. Here is the same while loop recoded to work that way (of course with such a simple condition to test we wouldn't bother to do it in this instance).

var i=0;
while (true) {
if (i >= 10) break;

Do While

The while loop discussed above tests the condition before running the code within the loop each time. If the condition is not met the first time it is tested then the content of the loop never gets run. Sometimes we want the loop to run at least one regardless. We can achieve this by shifting the test to the end of the loop like this:

var x = 12;
do {
} while (x<10)

In this example the loop will execute once even though the original value of x is greater than that tested for in the while condition.

Using What You Know

A while loop can easily be substituted whereever you have a for loop by moving the initialization statement in front of the loop and the increment statement to just inside the end of the loop. You may find that doing this makes the loop easier to read.

Past Lessons

  1. Introduction
  2. Decision Making
  3. Functions
  4. Maintain and Test
  5. External Script and Noscript
  6. Object Oriented Javascript

©2017 About.com. All rights reserved.