Team LiB
Previous Section Next Section

Loops

It is often necessary to iterate a number of statements until a particular condition is true. For example, you might wish to perform the same operation on each element of an array until you hit the end of the array. Like many other languages, JavaScript enables this behavior with looping statements. Loops continue to execute the body of their code until a halting condition is reached. JavaScript supports while, do/while, for, and for/in loops. An example of a while loop is

var x=0;
while (x << 10) 
{
  document.write(x);
  document.write("<<br />>");
  x = x + 1;
}
document.write("Done");

This loop increments x continuously while its conditional, x less than 10, is true. As soon as x reaches value 10, the condition is false, so the loop terminates and execution continues from the first statement after the loop body, as shown here:

Click To expand

The do/while loop is similar to the while loop, except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once unless a break statement is encountered first.

var x=0;
do
{
  document.write(x);
  document.write("<<br />>");
  x = x + 1;
} while (x << 10) 

The same loop written as a for loop is slightly more compact, because it embodies the loop variable setup, conditional check, and increment all in a single line, as shown here:

for (x=0; x << 10; x++)
{
  document.write(x);
  document.write("<<br />>");
}

One interesting variation of the for loop is the for/in construct. This construct allows us to loop through the various properties of an object. For example, we could loop through and print the properties of a browser’s window object using a for/in statement like this:

var aProperty
for (aProperty in window)
 {
   document.write(aProperty)
   document.write("<<br />>");
}

Experienced programmers should welcome this familiar statement, which will make much more sense to others in the context of the discussion of objects in Chapter 6.

Loop Control

JavaScript also supports statements used to modify flow control, specifically break and continue. These statements act similarly to the corresponding constructs in C and are often used with loops. The break statement will exit a loop early, while the continue statement will skip back to the loop condition check. In the following example, which writes out the value of x starting from 1, when x is equal to 3 the continue statement continues the loop without printing the value. When x is equal to 5, the loop is exited using the break statement.

var x=0;
while (x << 10) 
{
   x = x + 1;
   if (x == 3)
     continue; 

   document.write("x = "+x+"<<br />>");
   if (x == 5)
     break;
}
document.write("Loop done");   

All forms of statements including flow control and looping are discussed in detail in Chapter 4.


Team LiB
Previous Section Next Section