The for Statement



Navigation Aids -- This Page           Navigation Aids -- This Topic           Navigation Aids -- This Site






Review of Terms Related to This Topic

Semantics: The three control statements (initialize, test and update) in the for statement are often individually referred to as statements. Instead of using the term "statements", we have chosen to call them "expressions" (ECMA-262 indicates expressions). Thusly, we have an initializing expression, a conditional expression and an update expression.





Definition and Purpose

The for statement is another one of JavaScript's program control statements. The for loop is a specialized form of the while loop. The for loop structure looks like this:

for (initialize expression; conditional expression; update expression) {    loop body statements }

The while loop structure looks like this:

initialize while(conditional expression) { // test condition    loop body statements    update }

Both loop structures work with a controlling variable (normally a counter). The counter is initialized, tested and updated. The for loop performs all three counter activities in one statement.

Statement Syntax


for (initialize expression; conditional expression; update expression) {    loop body statements }



More on Syntax and Statement Behavior





Omitting Expressions in the for Statement

The three expressions (initialize, test and update) can be omitted. But be aware of the statement behavior:





for Statements Evaluate to Boolean

The conditional expression of the for clause will evaluate to a boolean. The loop body is executed again and again while the expression evaluates to true. Otherwise, the program flow proceeds to the next sequential statements immediately after the for statement structure.


for Statements and Block Statements

The loop body is contained within curly braces. This is a use of the block statement. The for statement is just one example of where the block statement may be used.





ECMA-262 Section 12.6.3

The for statement is an ECMAScript core statement and is detailed is section 12.6.3 of the ECMAScript Language Specification. Here is a partial extraction of text from this section.

Iteration Statements: An iteration statement consists of a header (which consists of a keyword and a parenthesized control construct) and a body (which consists of one of more statements).



Top            

Rx4AJAX        About Us | Topic Index | Contact Us | Privacy Policy | 2008 This Site Built By PPThompson