Core JavaScript 1.5 Reference:Statements:for
From MDC
Contents |
[edit] Summary
Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
| Statement | |
| Implemented in: | JavaScript 1.0, NES 2.0 |
| ECMA Version: | ECMA-262 |
[edit] Syntax
for ([initial-expression]; [condition]; [final-expression]) statement
[edit] Parameters
-
initial-expression - An expression (including assignment expressions) or variable declaration. Typically used to initialize a counter variable. This expression may optionally declare new variables with the
varkeyword. These variables are not local to the loop, i.e. they are in the same scope theforloop is in. The result of this expression is discarded.
-
condition - An expression to be evaluated before each loop iteration. If this expression evaluates to true,
statementis executed. This conditional test is optional. If omitted, the condition always evaluates to true. If the expression evaluates to false, execution skips to the first expression following theforconstruct.
-
final-expression - An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of
condition. Generally used to update or increment the counter variable.
-
statement - A statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a block statement (
{ ... }) to group those statements.
[edit] Examples
[edit] Example: Using for
The following for statement starts by declaring the variable i and initializing it to 0. It checks that i is less than nine, performs the two succeeding statements, and increments i by 1 after each pass through the loop.
for (var i = 0; i < 9; i++) {
n += i;
myfunc(n);
}