News Outline Schedule Tutorials Project Tools Links

1: While loops

The While loop is used to repeat a statement (or set of statements) until a certain condition is met. It has the following format:

while (condition) statement;

Where condition is a simple true or false comparison, and statement is either a single Javascript statement, or a group of them, enclosed by curly brackets {}. Note that the semicolon is not used until the end of the statement. The while loop is built in much the same way as an if statement, and works in a similar manner. First, the condition is tested, and if it contains a value of false, the loop never starts. If instead it contains a value of true, then the program executes the statement once, and returns to the beginning, to test the condition again. As long as the condition remains true, the loop will continue re-executing the statement. If you do not allow some way for the condition to be changed from true to false, your program will loop forever, potentially creating very unhappy users. Typically, inside of the loop, some code will make changes to one or more of the variables being used in the condition, so that it can be changed, and the program will be able to stop running the loop. Here is an example:

<html> <head> <title>Demo</title> </head> <body> <script type="text/javascript" > <!-- var firstvar; firstvar = "yes"; while (firstvar == "yes") { firstvar = window.prompt("Again?","yes"); }; document.writeln("All Done!"); // --> </script> </body> </html>

The above program will continue until the user enters something other than "yes" into the input window - however, if we had not set the value of firstvar to "yes" before entering the loop, it would never have done any of the things inside of the loop - this is because the while loop tests the condition at the START of the loop, and only enters it if the condition is true. Thus, the example below will not actually enter the loop:

<html> <head> <title>Demo</title> </head> <body> <script type="text/javascript" > <!-- var firstvar; firstvar = "nope"; while (firstvar == "yes") { firstvar = window.prompt("Again?","yes"); }; document.writeln("All Done!"); // --> </script> </body> </html>

2: The do/While loop

Obviously, there may be times when we don't want to have to set a variable before we start a loop, and we want to guarantee that the loop will be gone through at least once. To do this, we can use another kind of while loop, which does it's comparison at the end, like this:

do statement while (condition);

Again, where condition is a simple true or false comparison, and statement is either a single Javascript statement, or a group of them, enclosed by curly brackets {}. Note that the semicolon is not used until after the condition this time, instead of at the end of the statement. Here is an example:

<html> <head> <title>Demo</title> </head> <body> <script type="text/javascript" > <!-- var firstvar; do { firstvar = window.prompt("Again?","yes"); } while (firstvar == "yes"); document.writeln("All Done!"); // --> </script> </body> </html>

As you can see, in this case, we did not need to set a value to firstvar before we began the loop, because one is set for it inside of the loop.

3: For loops

While loops are very useful for repetitive tasks, however, when we want to repeat something only a certain number of times, they involve a lot of overhead, because we will have to set up variables and statements to keep track of how often we have gone through the loop, like this:

<html> <head> <title>Demo</title> </head> <body> <script language="javascript" type="text/javascript" > <!-- var count; count = 0; do { document.writeln("Count: " + count + "<br />"); count++; } while (count < 7); document.writeln("All Done!"); document.writeln("count now contains: " + count); // --> </script> </body> </html>

NOTE: count++ is a programming equivalent of typing the statement count = count + 1. Similarly, you could use count-- to represent count = count - 1.

Obviously, this can waste a lot of time, and for this reason, another type of loop exists, called a for loop. The for loop has the following form:

for ( initialization ; loopTest ; increment) statement;

Where initialization is a var statement which creates and sets the value of a variable, loopTest is a conditional comparison, just like in if and while statements, increment is a simple mathematical function to alter the counter variable, and statement is either a single Javascript statement, or a group of them, enclosed by curly brackets {}. Take careful note of all of the semicolons in the for statement - inside of the brackets of the for loop are actually three separate statements, and they must be separated from each other by semicolons. Here is an example:

<html> <head> <title>Demo</title> </head> <body> <script language="javascript" type="text/javascript" > <!-- for (var count = 0; count < 7; count++) { document.writeln("Count: " + count + "<br />"); }; document.writeln("All Done!"); document.writeln("count now contains: " + count); // --> </script> </body> </html>

4: break statements

One of the problems with a loop structure is that the check for the loop occurs in only one place - either the beginning, or the end of the loop. Sometimes you may want your loop to exit early, and for this reason, the break statement was introduced - it's purpose is to exit the current block of code, regardless of the type of block. A block of code is any set of JavaScript statements that are contained within a pair of curly brackets. {}.

First, we have an example of a program that wishes to allow the user to run a loop up to 7 times, but if they choose to exit early, we want to know how many times they actually ran the loop. In the example below, each piece of code that would be replaced by the break statement will be highlighted like this.

<html> <head> <title>Demo</title> </head> <body> <script language="javascript" type="text/javascript" > <!-- var count = 0; var howmany = 0; do { document.writeln("Count: " + count + "<br />"); if (!window.confirm("Continue?")) { count = 6; }; count++; howmany++; } while (count < 7); document.writeln("All Done!"); document.writeln("count now contains: " + count); document.writeln("<br />howmany now contains: " + howmany); // --> </script> </body> </html>

Note that even if we choose "Cancel" and don't want to keep going, the loop code will continue until it reaches the while statement, and will execute the rest of the contents of the loop for the current iteration.

Now here is the same program, changed to use the break command. As before, the sections now using the break command will be highlighted like this.

<html> <head> <title>Demo</title> </head> <body> <script language="javascript" type="text/javascript" > <!-- var count; count = 0; do { document.writeln("Count: " + count + "<br />"); if (!window.confirm("Continue?")) { break; }; count++; } while (count < 7); document.writeln("All Done!"); document.writeln("count now contains: " + count); // --> </script> </body> </html>

In the simple program above, there are only a few lines that are changed - the condition part of the has not changed, and the if statement now simply runs break as it's statement block, instead of altering the counter we were using, thus removing the need for another variable to track the "real" total, and reducing the complexity of our program.

Note that if the user clicks "Cancel", and the break statement is hit, the loop is exited before it reaches the statement count++;, so the last time through, nothing is added to total. If the user responds "Ok" all of the way through, they are told that count now contains 7, but if they exit earlier, the number reported will be lower, even though the while loop is not supposed to exit until the number is at least 7. This is an important difference from the previous case - the break command breaks the loop, and exits the loop construct immediately.