- Conditional Statements
- Loops and Control Structures
- How to Set and Use Timers
- Summary
- Q&A
- Workshop
- Exercises
Loops and Control Structures
The if statement can be thought of as a junction in program execution. Depending on the result of the test performed on the data, the program may go down one route or another with its execution of statements.
On many occasions, though, you might want to execute some operation a number of times before continuing with the rest of the program. If the number of repeats is fixed, you could perhaps achieve this with multiple if statements and incrementing counter variables, though the code would be messy and hard to read. But what if you don’t know how many times you need to repeat the piece of code because the number of repeats depends on, for example, the changing value of a variable?
JavaScript has various built-in loop structures that allow you to achieve such goals.
while
The syntax of the while statement is very much like the syntax for the if statement:
while(this condition is true) { carry out these statements ... }
The while statement works just like if too. The only difference is that, after completing the conditional statements, while goes back and tests the condition again. All the time the condition keeps coming up true, while keeps right on executing the conditional code. Here’s an example:
var count = 10; var sum = 0; while(count > 0) { sum = sum + count; count--; } alert(sum);
Each time while evaluates the condition as true, the statements in the curly braces are executed over and over, adding the current value of count to the variable sum on each trip around the loop.
When count has been decremented to zero, the condition fails and the loop stops; program operation then continues from after the closing brace. By this time, the variable sum has a value of
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 55
do ... while
The do ... while structure is similar in operation to while, but with one important difference. Here’s the syntax:
do { ... these statements ... } while(this condition is true)
The only real difference here is that, since the while clause appears after the braces, the list of conditional statements is executed once before the while clause is evaluated. The statements in a do ... while clause will therefore always be executed at least once.
for
The for loop is another loop similar in operation to while, but with a more comprehensive syntax. With the for loop, you can specify an initial condition, a test condition (to end the loop), and a means of changing a counter variable for each pass through the loop, all in one statement. Have a look at the syntax:
for(x=0; x<10; x++) { ... execute these statements ... }
You can interpret this as follows:
For x initially set to zero, and while x is less than 10, and incrementing x by 1 on each pass through the loop, carry out the conditional statements.
Let’s rewrite the example we gave when looking at the while loop, but this time using a for loop:
var count; var sum = 0; for(count = 10; count > 0; count--) { sum = sum + count; }
If the counter variable has not previously been declared, it is often convenient to declare it with the var keyword within the for statement instead of outside:
var sum = 0; for(var count = 10; count > 0; count--) { sum = sum + count; } alert(sum);
As in the previous example, after the loop terminates, the variable sum has a value of
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 55
Leaving a Loop with break
The break command works within a loop pretty much as it does in a switch statement: it kicks you out of the loop and returns operation to the line of code immediately after the closing brace.
Here’s an example:
var count = 10; var sum = 0; while(count > 0) { sum = sum + count; if(sum > 42) break; count--; } alert(sum);
You saw previously that, without the break instruction, the value of sum evolved like this:
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 55
Now, you find that when the value of sum reaches
10 + 9 + 8 + 7 + 6 + 5 = 45
the conditional clause of the if(sum > 42) statement will come up true and cause the loop to terminate due to the break command.
Looping Through Objects with for ... in
The for ... in loop is a special sort of loop intended for stepping through the properties of an object. Let’s see it in action applied to an array object in Listing 10.2.
LISTING 10.2 The for ... in Loop
<!DOCTYPE html> <html> <head> <title>Loops and Control</title> </head> <body> <script> var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']; var message = ""; for (i in days) { message += 'Day ' + i + ' is ' + days[i] + '\n'; } alert(message); </script> </body> </html>
In this sort of loop, you don’t need to worry about maintaining a loop counter or devising a test to see when the loop should complete. The loop will occur once for every property of the supplied object (in this example, once for every array item) and then terminate.
The result of running this example is shown in Figure 10.3.
FIGURE 10.3 Result of running the for ... in loop