for Loop

|

for Loop
A repeat loop cycles though a group of statements until some condition is met. For instance, you can use a repeat loop to cycle though an array and print it to the screen. Or, you might want to cycle though the Array and look for some specific information using the if statement. The for loop is the most common used repeat loop. Here is the syntax for it.

Syntax:
for ( [initial exp.]; [condition]; [update exp.] ){
statement(s)
}

The square bracket means that the parameter is optional. I always use all three parameters and think you will too.

The initial expression defines the starting point of the loop. It sets the value of a variable to some value. The condition tests the variable for a certain condition and when it is reached stops the loop and lets the code after for loop execute. The update expression determines how the variable is incremented.

Example:
Here is a simple example. We will use the "for loop" to print the numbers 1 through 5 to our screen.
var i
for(i=1; i<=5; i++){
document.write(i + "<BR>")
}

Results:
1
2
3
4
5

You can declare the variable as part of initial expression. In fact this is usually the way it is done. Here is our simple script with this change.

for(var i=1; i<=5; i++){
document.write(i + "<BR>")
}




 

©2009