| for The for statement is used to perform repeated executions of a given statement, for a set number of times. It is referred to as 'a for loop', and is used very often. The loop consists of three optional expressions which are enclosed in parentheses and separated by semi-colons. A chunk of code which will be executed is enclosed within the function, as per the syntax and example given below. syntax: for ( [initial statement;] [condition;] [num;] ) { statements; } EXAMPLE for (n = 0; n<9; n++) { document.write("This Loop Looped " + n + " Times."); } This example illustrates a loop which loops from n = 0 to n = 9. The value in the initial statement field is called a statement or variable declaration, and in this case is 'n = 0' which loads a value of '0' into the variable, 'n'. The statement in the condition field is n<9, which means that the value of n must be less than 9 - 8 is the highest it can go to and still evaluate to true. If the loop evaluates to true, the loop will iterate through itself until it evaluates to false. In this case, when the value of n reaches 9, the condition is then false. The value in the num field indicates that n must be incremented by one every time the loop iterates. This is accomplished through the use of the '++' (increment by one) operator. So then, in a nutshell, the statement is as follows: the variable n is intially loaded with a value of zero. This n value is incremented by one with every iteration. The condition will evaluate to true until the variable n reaches 9, at which time the condition will be false, and the enclosed statement will be executed. In this case, the statement to be executed will display as 'This Loop Looped 9 Times'. |