Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Using for Loops

The for keyword is the first tool to consider for creating loops. A for loop typically uses a variable (called a counter or index) to keep track of how many times the loop has executed, and it stops when the counter reaches a certain number. A basic for statement looks like this:

for (var = 1; var < 10; var++) {

There are three parameters to the for loop, separated by semicolons:

After the three parameters are specified, a left brace ({) is used to signal the beginning of a block. A right brace (}) is used at the end of the block. All the statements between the braces will be executed with each iteration of the loop.

The parameters for a for loop may sound a bit confusing, but once you're used to it, you'll use for loops frequently. A simple example of this type of loop is shown below:

for (i=0; i<10; i++) {
   document.write("This is line " + i + "<br>");
}

These statements define a loop that uses the variable i, initializes it with the value of zero, and loops as long as the value of i is less than 10. The increment expression, i++, adds one to the value of i with each iteration of the loop.

When a loop includes only a single statement between the braces, as in this example, you can omit the braces if you wish. The following statement defines the same loop without braces:

for (i=0;i<10;i++)
   document.write("This is line " + i + "<br>");

The loop in this example contains a document.write statement that will be repeatedly executed. To see just what this loop does, you can add it to a <script> section of an HTML document as shown in Listing 7.1.

Example 7.1. A loop using the for keyword

<html>
<head>
<title>Using a for Loop</title>
</head>
<body>
<h1>"for" Loop Example</h1>
<p>The following is the output of the
<b>for</b> loop:</p>
<script language="JavaScript" type="text/javascript">
for (i=1;i<10;i++) {
   document.write("This is line " + i + "<br>");
}
</script>
</body>
</html>

This example displays a message with the loop's counter during each iteration. The output of Listing 7.1 is shown in Figure 7.1.

07fig01.jpg

Figure 7.1 The results of the for loop example.

Notice that the loop was only executed nine times. This is because the conditional is i<10. When the counter (i) is incremented to 10, the expression is no longer true. If you need the loop to count to 10, you can change the conditional; either i<=10 or i<11 will work fine.

The structure of the for loop in JavaScript is based on Java, which in turn is based on C. Although it is traditionally used to count from one number to another, you can use just about any statement for the initialization, condition, and increment. However, there's usually a better way to do other types of loops with the while keyword, described in the next section.

Share ThisShare This

Informit Network