The JavaScript Diaries: Part 5 - Page 6 | WebReference

The JavaScript Diaries: Part 5 - Page 6


[previous] [next]

The JavaScript Diaries: Part 5

Loops

Loops are used to repeat a process or section of code a specified number of times. There are three types of loop statements: for, while, and do while. These statements use the increment/decrement and comparison operators we learned about previously.

The for Statement

A for statement is useful because it allows for the declaration of the variable, the condition for the statement, and the incremental expression all in one. The format of a for statement is:

  for (initialExpression; condition; incrementExpression) {
    statements
  }
  • The first portion declares the type of statement (e.g., for).
  • The next portion is the expression that is going to be used. It is declared as a variable.
  • Next, the condition that will be tested against the initial expression is given.
  • Finally, the incremental operator is given.

Here is a sample for statement. Be sure to try this yourself.

  for (var newNum=1; newNum < 4; newNum++) {
    document.write("This pass is #" + newNum + "<br>");
  }

Let's take a look at what's happening here.

  • The reserved word for begins the code for the loop.
  • Next, we declare the variable newNum and give it a value of 1
  • The first time the loop is executed, it will compare the initial value of the variable newNum with the conditional statement (newNum < 4). (This conditional statement is like an if statement: "If the variable newNum is less than four ....") If the conditional statement is false, the loop will not be executed. If the statement is true, the value will be used in the document.write statement. The value of the variable is not increased until after the loop executes once.
  • Next, the script will increase the value of the variable newNum by 1. It then executes the condition statement that we set-up which says: "As long as the value of the variable newNum is less than 4, perform the document.write statement." It will do this until the value of the variable newNum equals 4.
  • Once the value of the variable newNum equals 4, the loop will stop execution.

The ++ increment operator is used to increase the value of the variable by one. You can also use the decrement operator, --:

  for (var newNum=9; newNum>4; newNum--) {
    document.write("This pass is #" + newNum + "
"); }

If you needed to increase/decrease the value of the variable by a different number, say 3, you would write it as: newNum+=3 or newNum-=3, respectively.


[previous] [next]

Created: June 10, 2005

URL: