Web Development Tutorials




  
  

The for Statement

Unless instructed otherwise, a script executes its statements from top to bottom, one time through. When if statements are included in a script, this pattern will vary a little, with branching taking place before the script resumes its top-to-bottom journey. At times, though, you may need to run a particular section of code over and over again—to iterate, or loop through the code until some condition is met—before continuing the script sequence. This is where program loops come into play.

One way to repeat script operations is with the for statement. This statement establishes a program loop inside of which are statements that are executed repeatedly. The general format of the for loop is shown below.

for (initial expression; conditional expression; incremental expression) {
   //statements go here...
  }

Figure 5-1. General format for for statement.

The initial expression establishes a counter variable and sets it to an initial value. This index variable is used to keep track of the number of times the statements in the loop are executed. The conditional expression is a test to determine whether the statements in the loop should be executed. The test compares the current value of the counter with an ending value. If the ending value has not been reached, then the statements in the loop are executed. The incremental expression is a statement that increments the counter each time through the loop, advancing the counter from its initial value to its ending value. An example should help clarify this syntax.

function showLoop() {
  for (i=1; i<=5; i++) {
    alert ("This is loop #" + i);
  }
}

function init() {
  var showLoopBtn = document.getElementById("showLoopBtn");
  showLoopBtn.onclick=showLoop;
}

window.onload=init;

<input type="button" value="Show Loop" id="showLoopBtn" />

Listing 5-1. Code to demonstrate a for loop.

In this example, an alert box is displayed 5 times, each time displaying a message indicating the number of times the program loop has been executed. The alert() method is contained inside the braces defining the for loop, which has the following syntax:

for (i=1; i<=5; i++) {
	  //statements
  }

The statement includes three expressions, separated by semicolons, that serve to control the number of iterations of the loop.

  • The initial expression i=1 establishes an index variable named i and sets its value to 1, its initial value at the start of the loop.
  • The conditional expression i<=5 indicates the condition under which the statements in the loop are executed. As long as the value of i is less than or equal to 5, the loop is entered and its statements are executed.
  • The incremental expression i++ increments index i by 1 each time a loop is completed, and this value is tested to see if it is still less than or equal to 5. If this test is true, the loop is repeated.

Incidentally, variable i is used in this example as the loop index; you can choose your own variable name. It is conventional, and easy to type, to use variables such as i, j, and k as loop indexes.

Arithmetic Loops

The incrementing values of the loop index itself can be used in arithmetic expressions inside the loop. The following script uses this technique to display increasing powers of 2.



Figure 5-2. Displaying increasing powers of 2.

function showPowers() {
  document.getElementById("output").innerHTML = "";

  for (i=0; i<=8; i++) {
    document.getElementById("output").innerHTML += 
      2 + "<sup>" + i + "</sup> = " + Math.pow(2,i) + "<br/>";
  }
}


function init() {
  var showPowersBtn = document.getElementById("showPowersBtn");
  showPowersBtn.onclick=showPowers;
}

window.onload=init;

<input type="button" value="Powers of 2" id="showPowersBtn"/>
<span id="output"></span>

Listing 5-2. Code to display increasing powers of 2.

The showPowers() function sets up a for loop to increment variable i from 0 through 8. Each time through the loop, increasing powers of 2i are computed with Math.pow(2,i). That is, the powers of 20, 21, 22, and so forth are calculated and displayed as lines in the spanned output area. An output line is formatted by concatenating literal values, XHTML code, and the calculation.

String Loops

A loop counter can be used to increment through the characters in a text string. In the following example, the value in a text box is checked to see if it is in the format of an email address. This is determined by checking for the "@" character in the string.




Figure 5-3. Testing characters in a string.


function checkEmail() {
  var length = document.getElementById('email').value.length;
  var found = false;
  
  for (i=0; i<length; i++) {
    if (document.getElementById("email").value.charAt(i) == "@") {
      found = true;
    }
  }
	
  if (found == true) {
    alert("This is a valid email address.");
  } else {
    alert("This is not a valid email address.");
  }
}

function init() {
  var checkEmailBtn = document.getElementById("checkEmailBtn");
  checkEmailBtn.onclick=checkEmail;
}

window.onload=init;

<input id="email" type="text"/>
<input type="button" value="Check valid Email" id="checkEmailBtn"/>

Listing 5-3. Code to test characters in a string.

The checkEmail() function sets up a for loop to increment through each of the characters appearing the the text box. First, however, the number of characters in the field needs to be determined to know how many times to iterate the loop. This value is given by the statement,

var length = document.getElementById("email").value.length

which assigns the length property of the value in the field to variable length. Recall that characters in a string are numbered beginning with 0. Therefore, the loop index needs to increment from 0 (the position of the first character) through one less than the length of the string in order to step sequentially through each of its characters.

for (i=0; i<length; i++) {
  //statements
}

Also, it is necessary to keep track of whether a match is found for the "@" character. This is the purpose of the found variable. It is a program flag, an indicator of whether or not a match was found. Prior to starting the for loop, this found flag is initialized to the Boolean value false. This is the initial "found" condition. If, during the program loop, a match is found to the "@" character, then the found flag is changed to true, indicating that a match was made. If, however, no match was found, then the Found flag retains its original false setting when the loop ends.

Inside the for loop an if statement checks each character in the string to see if it is the "@" character.

if (document.getElementById("email").value.charAt(i) == "@") {
  found = true;
}

The string method charAt(i) points to the character at position i as this loop counter increments through each character in the string. If the character at position i is the "@" character, then the found flag is set to signal its match.

After the for loop has finished, the script checks to see whether it should display an alert message announcing a valid or invalid email address. If the found flag has been changed to true, a confirmation message is display; if the flag still contains false, then the address is invalid.


if (found == true) {
  alert("This is a valid email address.");
} else {
  alert("This is not a valid email address.");
}

Since the found flag itself contains a true or false value, this test can be expressed as simply

if (found)

The for loop is the most common of JavaScript iterations. However, its use is constrained to knowing in advance the number of iterations needed. An ending value for the loop index, either fixed or calculated, is required. In some situations this ending value cannot be known, for example, in an iteration that depends on a user event to halt it. For these types of iterations, a different type of loop is required.


TOP | NEXT: while() Statements