The for Loop


The for Loop

The most common loop is the for loop, which enables you to execute a series of statements a specific number of times. Here's the syntax of this loop:

 for ([initial-expression]; [condition]; [increment-expression]) {      statements  } 

This loop enables you to use the three expression in parentheses to control the number of times the statements are executed. These statements make up the loop's body. Here's what the parts of this loop are all about:

  • initial-expression . This part enables you to perform any initialization you'll need for the loop, and you can even declare new variables here using the var keyword.

  • condition . This is an expression evaluated on each pass through the loop. If this condition evaluates to true, the statements are performed; otherwise the loop terminates. The condition in a for loop often involves checking the value in a loop index variable, which is incremented each time through the loop and so keeps track of the number of times the loop has executed.

  • increment-expression . Performed after the body of the loop is executed. Usually used to increment a loop index, which counts the number of times the loop has executed.

  • statements . This is the loop's body , a set of statements that are executed as long as condition evaluates to true. Although not required, it's usually good practice to indent these statements.

Tip

You can omit any of the initial-expression , condition , or increment-expression parts of a for loop, but you must not omit any of the semicolons separating these parts. If you omit the condition part, it always evaluates to true.


The for loop has always been a part of JavaScript, as you see in Table 3.1.

Table 3.1. The for Loop

Statement

NS2

NS3

NS4

NS6

IE3a

IE3b

IE4

IE5

IE5.5

IE6

for

x

x

x

x

x

x

x

x

x

x

The for loop is usually used with a loop index (also called a loop counter ), which is just a variable that keeps track of the number of times the loop has executed. Here's an example. Suppose that I want to add the numbers from 1 to 5. To do that, I can use a loop index I'll call loopIndex to count the number of times the loop has executed, called iterations . I can start by declaring loopIndex and setting it to 1 in the initialization part of the for loop:

 var loopIndex  for (  loopIndex = 1;  ...) {          .          .          .  } 

This means that the first time through the loop, loopIndex will have a value of 1. In this example, we'll increment loopIndex by 1 each time through the loop, and to stop when we've added the numbers up to 5, we can set the termination condition to loopIndex < 6 . While this condition is true, the loop will execute the statements in its body; and as soon as loopIndex equals or exceeds 6, the loop will stop. Here's how we put this condition into our for loop:

 for (loopIndex = 1;  loopIndex < 6;  ...) {          .          .          .  } 

After the loop's body is executed, we have a chance to increment loopIndex in the increment-expression part of the for loop. This expression doesn't actually have to increment anythingit can be any expression you wantbut because for loops are usually written to use a loop index/counter of some kind, this is where you usually increment that counter, as follows :

 for (loopIndex = 1; loopIndex < 6;  loopIndex++  ) {          .          .          .  } 

The way we've set up this loop, then, means that the first time through the loop, loopIndex will be 1, the next time 2, and so on up to 5, after which the loop terminates. Therefore, we can add the numbers 1 to 5 just by adding the current value of loopIndex to a running total in the loop's body, like this:

(Listing 03-01.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Using the for Loop          </TITLE>      </HEAD>      <BODY>          <H1>Using the for Loop</H1>          <SCRIPT LANGUAGE="JavaScript">              <!--  var loopIndex, total   total = 0   for (loopIndex = 1; loopIndex < 6; loopIndex++) {   total += loopIndex   document.write("Loop iteration: "   + loopIndex + " Total: "  + total + "<BR>")   }  // -->          </SCRIPT>      </BODY>  </HTML> 

Figure 3.1 shows the results of this code. The program displays the value of both loopIndex and the running total all the way through the loop. Our first for loop works as expected.

Figure 3.1. Using a for loop in the Netscape Navigator.

graphics/03fig01.gif

Using Local Variables in for Loops

You should be aware of a couple of shortcuts herefor example, we've used only the loopIndex variable in the for loop itselfand we can actually declare it in the for loop itself, using the var keyword. Here's how that looks:

 <HTML>      <HEAD>          <TITLE>              Using the for Loop          </TITLE>      </HEAD>      <BODY>          <H1>Using the for Loop</H1>          <SCRIPT LANGUAGE="JavaScript">              <!--             var total              total = 0  for (var loopIndex = 0; loopIndex < 6; loopIndex++) {  total += loopIndex                  document.write("Loop iteration: "                      + loopIndex + " Total: "  + total + "<BR>")              }              // -->          </SCRIPT>      </BODY>  </HTML> 

This loop works as before. In fact, using the comma operator we saw in the preceding chapter, we also can declare and initialize the running total variable, total , in the for loop, like this:

  for (var loopIndex = 1, total = 0; loopIndex < 6; loopIndex++) {  total += loopIndex      document.write("Loop iteration: "          + loopIndex + " Total: "  + total + "<BR>")  } 

Using Arrays in for Loops

A primary use of for loops is to handle the data in an array. You can see how this would work wellyou can access the data using a numeric index, and for loops can use a numeric loop index. This means you can iterate over all the data in an array just by using the array's length (which you can find with the array's length property) as the maximum possible value for the loop index. Here's an example showing how this worksjust like the preceding example, we're adding the numbers from 1 to 5 here, but this time, those numbers are in an array named data :

(Listing 03-02.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Using the for Loop With an Array          </TITLE>      </HEAD>      <BODY>          <H1>Using the for Loop With an Array</H1>          <SCRIPT LANGUAGE="JavaScript">              <!--  var data = new Array(1, 2, 3, 4, 5)   for (var loopIndex = 0, total = 0; loopIndex < data.length; loopIndex++) {   total += data[loopIndex]   }   document.write("The total is " + total + ".<BR>")  // -->          </SCRIPT>      </BODY>  </HTML> 

Figure 3.2 shows the results.

Figure 3.2. Using a for loop with an array in the Netscape Navigator.

graphics/03fig02.gif



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net