Loop Statements
Sometimes you will need to repeat an operation multiple times until a certain condition is true. As you will see in Chapter 5, "An Introduction to Arrays," this is especially important when you need to work with data stored in arrays. The types of statements used to accomplish repetitive loops are called loop statements. An integral part of these statements is comparison and increment operators discussed in Chapter 2.
There are three types of loop statements: the while statement, the do while statement, and the for statement. Let's look at the while statement first.
The while Statement
The while statement is the easiest of the looping statements to understand and use. Although it performs a different task, its structure is similar to the if statement:
while (expression) statement
or
while (expression) statement
Like all the looping statements, the first thing the while statement does is evaluate the expression contained within its parentheses to see whether the expression evaluates to true or false. If the expression evaluates to true, the while statement evaluates its statement(s). Where it differs from the statements that you have seen before is that it then goes back to recheck its expression. If the expression is true, then the JavaScript interpreter will execute the statement(s) in the statement block and it will evaluate the expression in parentheses again. The JavaScript interpreter will continue to loop in this way until the expression evaluates to false.
Clearly, if the while statement isn't to loop infinitely something in the expression has to change. This is achieved by including a variable in the expression that is changed by one of the statements evaluated by the loop during each evaluation. For example take a look at the following code:
var loopCounter = 0; while (loopCounter <= 3) alert(loopCounter++);
This causes the display of four alert boxes in succession with the numbers 0, 1, 2 and 3 respectively. After the fourth alert has been displayed the variable loopCounter will contain a value of 4, so when the expression loopCounter <= 3 is evaluated, it returns false. Therefore, the while loop is not executed again and control passes to the statement that follows the while statement.
In Chapter 2 you learned that increment and decrement operators (++ and -- respectively) can be used to increment or decrement the value of their operand by 1. As you can see, this is especially useful in loops such as the one above. Every time the above alert is evaluated the value of the variable loopCounter is increased by 1. Therefore, after four loops the value of loopCounter is no longer less than or equal to three. Hence the expression evaluates to false, causing the while statement to stop looping, at which point evaluation will continue at the code following the while statement.
It is uncommon to actually use a long variable name such as loopCounter because they are extensively used in the statements belonging to the loop statement. It is standard practice to give counter variables the names i, j, and k so as to keep the code as uncluttered as possible. But note this is the only time that it is considered acceptable to give variables such nondescript names.
CAUTION
You must be careful that the variable in the expression changes each time so eventually it will cause the expression to evaluate to false. If you don't change the variable in the expression, the while statement will loop infinitely preventing any other scripts from running and, in some older browsers, will cause the browser to crash. This can happen if you forget to include a statement that increments/decrements the variable, or if you increment/decrement it in the wrong direction!
Generally, when you use the while statement you will want it to loop through more than just one line of code. To do this, include the curly braces as usual to create a statement block belonging to the while statement. For example, you could have written the above example like this:
var loopCounter = 0; while (loopCounter <= 3) { alert(loopCounter); loopCounter++; }
The do while Statement
The do while statement is very similar to the while statement. The difference is that the expression is evaluated at the end of the statement. In other words, the statement block is always evaluated once before the expression is evaluated. The structure of a do while statement is shown below:
do statement while (expression);
The major effect of having the expression at the end of the loop is that the statements contained by the do while statement will be evaluated at least once before the expression is evaluated to decide whether it should loop again. For example try out the following code:
do alert("Statement evaluated!"); while (false);
As you will see, the alert box displays once regardless of the fact that the expression is simply the value false. Other than this, there is no difference between the way the while statement and the do while statement work.
If you want a do while statement to control multiple statements use a statement block, like this:
do { statement1 statement2 ... statement5 } while(condition);
CAUTION
Because the do while statement does not end with a closing curly brace, it requires a semicolon after the closing parenthesis. Forgetting to include the semicolon may cause an error.
The for Statement
The while and do...while statements have three essential elements: a statement that sets the initial value of a counter; an expression that tests a condition; and an expression that increments the counter. It can be easy to forget one or other of these when you are quickly typing out a piece of code, and you could end up with problems such as infinite loops. Fortunately, there is an alternative in the form of the for statement, which can contain all these elements in one place. It is written with the following structure:
for (setInitialCounterValue; testCondition; changeCounterValue) statement
Because all three of the essential parts of a loop statement are located between the parentheses, the for loop is much more popular than the other two methods because it is easier to follow the logic that controls the looping.
NOTE
The for statement can govern multiple statements by enclosing them in a statement block.
Here's a simple example that would display three alert boxes:
for (var i=0; i<3; i++) { alert(i); }
The first statement in the parentheses declares and assigns to the variable i an initial value. It is this variable that then acts as the loop counter. Note that it is only evaluated at the beginning of the first loop. The second statement is the condition for the loop. Each time a loop finishes it is checked again to determine whether another loop should be made. Finally there is the third statement. It declares how the loop counter should be incremented (or decremented).
NOTE
Note that the three elements inside the parentheses are statements. Therefore, semicolons separate them and not commas. Remember this is how more than one statement can be placed on a single line.
CAUTION
The variable used for the loop counter in a for statement is inside the parentheses so it can only be incremented using the increment and decrement operators ++ and -- or the full syntax equivalent to increase the value of the loop counter.
To get some experience using the for statement, let's try to use it to create a page that will generate a simple multiplication table. First, we will ask a user which multiplication table he wants to see; then we will output the first 12 lines of that multiplication table in an alert box.
The first thing we will need to do is ask the user to enter the multiplication table that he wants. This can be done using a prompt box that assigns the value to a variable we will call multTable. See the following example:
var multTable = prompt("Please enter the table.", "");
What about generating the table? We could write out each of the 12 lines concatenating each one to a variable. But this would be very inefficient. A better way would be to use a loop statement. To do that let's choose the for statement.
For the moment, let's ignore the statement needed for the statement block and concentrate on the for statement itself. We probably want to start at 1 so this can be the initial value of our counter i, and we know when we want to stop once we get to 12. With this in mind our for loop will need to look something like this:
for (var i=1; i<=12; i++) { statement; }
Okay, that's fairly easy so far, but what about the statement the for loop controls? Well, to help decide what it should look like, it is useful to take a look initially at the first few lines of a multiplication table. Let's take the 2 times table as an example:
1 x 2 = 2 2 x 2 = 4 3 x 2 = 6
Looking at the table, you can see that the first element of each line increments by 1. To recreate this with each iteration of the loop, you could quite easily use the counter i.
The next three characters are always the same. The x and the equal sign could be created simply by using two strings, but the number in between depends on which table the user asks for. It's not much of a problem though as that value can simply be found in the variable multTable. Let's take a look at how our statement looks so far:
i + " x " + multTable + " = "
We are just concatenating all the components of the line together. But how do we actually add the answer to the end? Well actually it isn't too hard if you think about it. What we have on the left-hand side of the equal sign is exactly what generates the answer: i multiplied by the variable multTable. This is all that is needed to finish the statement. Well, almost. We will also want to include a new line character to make sure each line of the table is actually displayed on a new line. This is done with the escaped character \n. Our statement now looks like this:
i+ " x " +multTable+ " = " +(i*multTable)+ "\n";
During each iteration through the for loop, you will need to concatenate the line to a variable, which builds up the table. Call this variable theTable and your completed statement will look like this:
theTable += i+ " x " +multTable+ " = " +(i*multTable)+ "\n";
With this statement in place within the loop, and an alert for theTable after the loop, a multiplication table will be generated. If you also store the entire piece of code within a function, it will allow users to request a different table as many times as they like. If you use a hyperlink to call the function, Listing 3.6 shows how your finished page might look:
Listing 3.6 Multiplication Table Generator (multTableGenerator.htm)
<html> <head> <title>Multiplication Table Generator</title> <script language="javascript" type="text/javascript"> <!-- function generateTable() { var multTable = prompt("Please enter the table.", ""); var theTable = ""; for (i=1; i<=12; i++) { theTable += i+ " x " +multTable+ " = " +(i*multTable)+ "\n"; } alert(theTable); } //--> </script> </head> <body> <h1>Multiplication Table Generator</h1> <a href="javascript:generateTable()">Create New Table</a> </body> </html>
Try it yourself.
Before you finish, it is worth mentioning that a statement that is related to the loop statements is the break statement. Remember that the break statement allows you to prematurely break out of conditional statements. There is a similar statement for the loop statements called the continue statement. However, rather than breaking out of the loop altogether and carrying on evaluation further down the page, it simply prevents evaluation of any remaining statements in the statement block. The loop continues to check the condition at the top of the loop to see whether it should loop again. Later in the book you will learn just how this can be useful.
The for in Statement
A second use of the for loop is to loop through the properties and child objects of an object. Objects are the JavaScript entities that allow you to apply these tools to making a difference to your Web pages, and to a certain extent the browser. (Objects will be covered in the next chapter.)