In Lesson 3, you learned how functions can greatly clean up your code by encapsulating repetitive operations and calculations to use throughout the application's code. There are times, however, when a function isn't the right tool for handling repetitive code.
For example, you want a particular line of code repeated 10 times — no more and no less. You can, of course, write that same line of code 10 times, but in doing so you condemn yourself to a maintenance nightmare in which you may have to make 10 changes to 10 lines of code. Functions don't solve the problem either. Although the code might be a little less complex, you still have to type (or copy and paste) 10 identical lines of code.
For this reason, programming languages have a concept called looping. In programming, looping means to repeat one or more lines of code while a particular condition is true
. This functionality is useful, and you'll see loops used throughout the book. But for now, let's take a look at some loops.
There are several different types of loops, but they all perform the same primary function of repeating code. They also share some similar features. For example, all loops repeat a code block based on the results of a condition. As long as the condition evaluates to true
, the loop iterates, or repeats its code, and it immediately ends when the condition evaluates to false
.
Loops can be grouped into two categories: pre-test and post-test. A pre-test loop tests its condition at the beginning of every iteration of the loop — even the first iteration. It's entirely possible for a pre-test loop to not execute its block of code at all. If the condition fails on the first iteration, the loop doesn't execute any code.
A post-test loop tests its condition at the end of each iteration. This means that a post-test loop's code block is executed at least once. After the code block executes, JavaScript evaluates the loop's conditional logic and determines whether the loop continues or exits.
Loops, while useful, can sometimes cause trouble when you're developing an application. Remember that loops repeat their code over and over again until their provided condition returns false
. It is very easy to miss a flaw in the condition's logic and cause the loop to never end. This type of error is referred to as an infinite loop, and it is very common when applications are being developed. Always double-check the loop condition's logic; it can save you a lot of debugging time, or time spent locating and fixing errors.
It is also possible to break out of a loop early by using the break
statement introduced with the switch
statement in Lesson 4, and you can skip iterations by using a continue
statement.
Let's now look at the different types of loops starting with the for
loop.
The for
loop's primary function is to repeat code a specified number of times. The for
keyword denotes a for
loop, which is followed by the loop's logic contained within parentheses. This logic consists of the following three things:
The following is an example of the for
loop's syntax:
for (var loopCounter = 0; loopCounter < 10; loopCounter++) { alert("This is loop iteration: " + loopCounter); }
Focus on the logic inside the parentheses. The initialization, condition, and increment statement are separated by semicolons. The loop counter (the loopCounter
variable, but it can be any variable) is initialized with a value of 0
. Computer scientists begin counting at 0
instead of 1
mainly because of the binary system that all computers are based upon. This is counter to what we humans have done for centuries; so it does take a while to get used to.
Counters do not have to start at 0
; they can start at any integer value.
After the counter initialization is the condition. As long as the condition results in true
, the loop iterates and repeats the code within the code block. If false
, the loop immediately exits. The for
loop is a pre-test loop; therefore, it can execute zero or more times. In this example the loop iterates as long as loopCount
is less than 10
. The loop ends once loopCount
equals 10
or more.
Following the condition is the increment portion of the loop's logic. The code here increments the loop counter by one at the end of each iteration of the loop. In this example you see a new operator, the increment operator (++
). The increment operator is a unary operator that adds one to the value contained in the variable. The code loopCounter++
is equivalent to loopCounter = loopCounter + 1
.
The increment operator is a special unary operator in that it can either precede or follow the variable to be incremented: ++loopCounter
and loopCounter++
are both valid statements. Where the increment operator is placed determines how the value is incremented. If it is placed before the variable (++loopCounter
), the value contained within loopCounter
is incremented by one, and the new value is returned to the caller. Consider the following code as an example:
var x = 1; var y = ++x; // returns 2
Here a variable called x
is initialized with a value of 1
. In the second line the increment operator precedes the x
variable. The value in x
is incremented, and the new value of x
is assigned to the y
variable. So y
contains a value of 2
. Contrast that example with what happens when the ++
operator follows the variable, as shown here:
var x = 1; var y = x++; // returns 1, but x is now 2
As in the previous example, this code initializes the x
variable with a value of 1
. In the second line, the current value of x
(which is 1
) is assigned to y
, and then x
is incremented by one to 2
. So y
contains 1
, while x
contains 2
.
It's important to understand the difference between ++loopCounter
and loopCounter++
, as unexpected results may occur if the increment operator is placed incorrectly.
There is also a decrement operator: --
. Instead of increasing by one, it decreases by one. It too can be placed before or after the variable, and other than decreasing by one, it behaves the same as the increment operator.
It's important to note that an increment or decrement operator does not have to be used in the increment portion of the for
loop. You can increment the loop counter however you want to — with addition, subtraction, multiplication, or division. Look at the following code as an example:
for (var loopCounter = 0; loopCounter < 10; loopCounter = loopCounter * 2) { // code to repeat here }
Here loopCounter
is increased by being multiplied by 2
every time the loop iterates. But there's a flaw in the logic of this particular implementation. The loopCounter
variable is initialized as 0
. When loopCounter
is incremented, 0
is multiplied by 2
, resulting in 0
. So loopCounter
always has a value of 0
, which is less than 10, and that means the loop runs forever.
The for
loop is especially useful when you know exactly how many times to execute the same block of code, but sometimes you just need a loop that iterates as long as a condition is true
. Enter the while
loop.
The while
loop is simpler than the for
loop. It does not require counters to function properly; all it needs is a condition. It is possible, however, to replicate the for
loop's functionality with the while
loop.
The while
loop is a pre-test loop, so JavaScript tests the condition before the loop iterates. The loop's syntax looks like this:
while (condition) { // statements }
It begins with the while
keyword followed by conditional logic in parentheses and then the block of code that the loop repeats. Using the while
loop can be as simple as the following example:
var counter = 0; while (counter < 5) { alert(counter); counter++; }
This code initializes the counter
variable with a value of 0
. To determine if the loop should execute code, the value of counter
(currently 0
) is compared to the number 5
. If the comparison results in true
, then the code within the loop's code block executes. An alert window displays the value of counter
, and counter
is incremented via the ++
operator. As long as counter
is less than 5
, the loop executes. Otherwise the loop exits and JavaScript begins executing the next line of code after the loop.
The do-while
loop is a post-test loop: its condition is tested at the end of each iteration. Other than that, the do-while
loop is similar to the while
loop. This type of loop is useful when you know you want the loop to iterate at least once.
The syntax of the do-while
loop looks like this:
do { // statements } while (condition);
With this loop, the code within the do
block executes at least once, and then the condition is evaluated to determine if the loop iterates or exits. Notice the semicolon at the end of the while
statement. This is the only time a semicolon is used to terminate a loop statement.
Look at this example of an implementation of the do-while
loop:
var counter = 0; do { alert(counter++); } while (counter < 5);
This code results in the same outcome as the example for the while
loop. First the counter
variable is initialized with a value of 0
. Then the code within the do
code block is executed; it uses an alert window to display the value of counter
and increments the variable in the same statement. Then the condition tests if the loop should continue or exit.
In this lesson you learn about looping with the for
, while
, and do-while
loops. You will write an HTML page and a JavaScript file for each loop.
For this lesson, you need a text editor; any plain text editor will do. For Microsoft Windows users, Notepad is available by default on your system or you can download Microsoft's free Visual Web Developer Express (www.microsoft.com/express/web/
) or Web Matrix (www.asp.net/webmatrix/
). Mac OS X users can use TextMate, which comes as part of OS X, or they can download a trial for Coda (www.panic.com/coda/
). Linux users can use the built-in VIM.
You also need a modern web browser. Choose any of the following:
Internet Explorer 8+
Google Chrome
Firefox 3.5+
Apple Safari 4+
Opera 10+
Create a subfolder called Lesson05
in the JS24Hour
folder you created in Lesson 1. Store the files you create in this lesson in the Lesson05
folder.
Use a for
loop and keep a running total of the even numbers from 0 to 20. In other words, add each even number together to get a total. Use the continue
statement to achieve this. Use alert()
to display the grand total when the loop exits.
Open your text editor and type the following code. Use the name i
for the counter variable, and the name total
for the variable that keeps track of the total.
var total = 0; for (var i = 0; i < 20; i++) { } alert(total);
Add the bold line in the following code to the file. This line calculates total
:
var total = 0;
for (var i = 0; i < 20; i++) {
total = total + i;
}
alert(total);
This code adds the counter to total
in each iteration of the loop. You want only the even numbers, so use the continue
statement to skip an iteration when i
is odd. Add the following bold lines of code:
var total = 0; for (var i = 0; i < 20; i++) {if (i % 2) {
continue;
}
total = total + i; } alert(total);
This code uses the modulus operator to determine whether i
is even or odd. Remember, modulus operations return 0
if i
is even. Because 0
is a false value, the continue
statement is not executed. If i
is odd, however, the modulus operation returns a nonzero number — a truth value. So, when that's the case, the continue
statement executes and causes the loop to skip the current iteration.
Save the file as lesson05_sample01.js
.
Open another instance of your text editor, type the following HTML, and save it as lesson05_sample01.htm
.
<html> <head> <title>Playing with for loops</title> </head> <body> <script type="text/javascript" src="lesson05_sample01.js"></script> </body> </html>
Open the HTML file in your browser. An alert window will display the value 190
.
Write a simple application using the while
loop. The application should prompt the user to enter his or her name. The loop will use an alert window to display a greeting to the user, as well as a counter value, and it will continue to loop until the user types exit
. The counter variable's name is i
, and the variable to hold the user's name is userName
.
Open your text editor and type the following code:
var i = 0; var userName = prompt("Please enter your name. Type exit to exit", ""); while (userName !== "exit") { }
Add the following bold lines to the file. The first line uses an alert window to display the message to the user. This line concatenates several string literals with the value the user typed, as well as incrementing the i
variable by one. The increment operator is used before the variable to display a number to the user starting with 1
. The second line prompts the user to enter his or her name again.
var i = 0; var userName = prompt("Please enter your name. Type exit to exit", ""); while (userName !== "exit") {alert("Hello, " + userName + ". You've run this " + ++i + " times.");
userName = prompt("Please enter your name. Type exit to exit", "");
}
Save the file as lesson05_sample02.js
.
Open another instance of your text editor, type the following HTML, and save it as lesson05_sample02.htm
.
<html> <head> <title>Playing with while loops</title> </head>
<body> <script type="text/javascript" src="lesson05_sample02.js"></script> </body> </html>
Open the HTML file in your browser and enter a few names. Then, type exit
to exit the loop.
Rewrite the while
loop example using the do-while
loop.
Open your text editor and type the following code. Save the file as lesson05_sample03.js
.
var i = 0; do { var userName = prompt("Please enter your name. Type exit to exit", ""); alert("Hello, " + userName + ". You've run this " + ++i + " times."); } while (userName !== "exit");
Open another instance of your text editor, type the following HTML, and save it as lesson05_sample03.htm
.
<html> <head> <title>Playing with do-while loops</title> </head> <body> <script type="text/javascript" src="lesson05_sample03.js"></script> </body> </html>
Open the HTML file in your browser and enter a few names. Then type exit
to exit the loop. Notice that the alert window displays a greeting for exit
. You can fix this behavior by using an if
statement to determine if exit
was typed. Add the bold lines from the following listing, save the JavaScript file, and reload the web page.
var i = 0; do { var userName = prompt("Please enter your name. Type exit to exit", "");if (userName !== "exit") {
alert("Hello, " + userName + ". You've run this " + ++i + " times.");}
} while (userName !== "exit");
Please select Lesson 5 on the DVD to view the video that accompanies this lesson. You can also download the sample code for all lessons from the book's website at www.wrox.com
.
3.144.172.38