Develop a new think

For loop

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.

Syntax Switch

for (initial expression; conditional expression; incremental expression)
  {
   do this...
  }

Example

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.

<script type="text/javascript">

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

</script>

<input type="button" value="Show Loop" onclick="ShowLoop()"/>
-- 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++)
  {
  }

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.



-- Displaying increasing powers of 2.
<script type="text/javascript">

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/>";
  }
}

</script>

<input type="button" value="Powers of 2" onclick="ShowPowers()"/>
<span id="Output"></span>
-- 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.

  


<script type="text/javascript">

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.");
  }
}
</script>

<input id="Email" type="text"/>
<input type="button" value="Check valid Email" onclick="CheckEmail()"/>

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++)
  {
  }

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.

web counter