Sams Teach Yourself JavaScript in 24 Hours Free Open Book

Sams Teach Yourself JavaScript in 24 Hours

Previous Page
Next Page

Using for Loops

Loops are useful any time you need a section of code to execute more than once. The for keyword is the first tool to consider for creating loops. A for loop typically uses a variable (called a counter or an 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:

  • The first parameter (var = 1 in the example) specifies a variable and assigns an initial value to it. This is called the initial expression because it sets up the initial state for the loop.

  • The second parameter (var < 10 in the example) is a condition that must remain true to keep the loop running. This is called the condition of the loop.

  • The third parameter (var++ in the example) is a statement that executes with each iteration of the loop. This is called the increment expression because it is typically used to increment the counter. The increment expression executes at the end of each loop iteration.

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. Here is a simple example of this type of loop:

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. Because this happens at the end of the loop, the output will list the numbers zero through nine.

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

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

Did you Know?

It's a good style convention to use braces with all loops whether they contain one statement or many. This makes it easy to add statements to the loop later without causing syntax errors.


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.3.

Listing 7.3. 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.3 is shown in Figure 7.2.

Figure 7.2. 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.

By the Way

You might notice that the variable name i is often used as the counter in loops. This is a programming tradition that began with an ancient language called Forth. There's no need for you to follow this tradition, but it is a good idea to use one consistent variable for counters. (To learn more about Forth, see the Forth Interest Group's website at www.forth.org.)


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.

Previous Page
Next Page
Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Y]


     Main Menu
Sams Teach Yourself JavaScript in 24 Hours
Table of Contents
Copyright
About the Author
Acknowledgments
Part I: Introducing the Concept of Web scripting and the JavaScript Language
Part II: Learning JavaScript Basics
Hour 5. Using Variables, Strings, and Arrays
Hour 6. Using Functions and Objects
Hour 7. Controlling Flow with Conditions and Loops
The if Statement
Using Shorthand Conditional Expressions
Testing Multiple Conditions with if and else
Using Multiple Conditions with switch
Using for Loops
Using while Loops
Using do…while Loops
Working with Loops
Looping Through Object Properties
Summary
Q&A
Quiz Questions
Quiz Answers
Exercises
Hour 8. Using Built-in Functions and Libraries
Part III: Learning More About the DOM
Part IV: Working with Advanced JavaScript Features
Part V: Building Multimedia Applications with JavaScript
Part VI: Creating Complex Scripts
Part VII: Appendixes
Index


More Books
PHP Hacks
Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
The Koran (Holy Qur'an)
Macromedia Flash 8 Bible
Search Engine Optimization for Dummies
YouTube Traffic
PHP 5 for Dummies
Harry Potter and The Chamber of Secrets
Harry Potter and the Sorcerer's Stone
The Pilgrim's Progress
Wireless Hacks
Flash Hacks. 100 Industrial-Strength Tips & Tools
PayPal Hacks. 100 Industrial-Strength Tips and Tools
Amazon Hacks
Pdf Hacks
The Da Vinci Code
Google Hacks
The Holy Bible
Windows XP For Dummies
Harry Potter and the Half-Blood Prince
Seo Book
Upgrading and Repairing Networks
Macromedia Dreamweaver 8 UNLEASHED
Windows XP Annoyances
Windows XP Hacks
Microsoft Windows XP Power Toolkit
Teach Yourself MS Office In 24Hours
iPod & iTunes Missing Manual
PC Hacks 100 Industrial-Strength Tips and Tools
PC Overclocking, Optimization, and Tuning - 2th Edition
PC Hardware In A Nutshell 3rd Edition
PC Hardware in a Nutshell, 2nd Edition
Upgrading and Repairing PCs
Google for Dummies
MySQL Cookbook
Teach Yourself Macromedia Flash 8 In 24 Hours
PHP CookBook
Sams Teach Yourself JavaScript in 24 Hours
PHP5 Manual
Free Games Paper Airplanes
500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele