An iteration statement executes a body of code iteratively - that is, over and over again, while a certain condition is true or until a terminating condition becomes true.
An iteration statement consists of a header and a body. The header is a keyword and a set of control parameters in parentheses. The body is a statement block enclosed in braces.
The following iteration statements are supported by ECMA compliant implementations:
while()
for ()
for( ... in)
All of these loop-controlling statements test the condition each time round the loop. In the case of some iterators, the test happens before the code is executed. For others it happens after the code has been executed.
An infinite loop is one for which the terminating condition never happens or where the iterating condition remains true forever.
Here are some infinite loops:
for(;;) { // do this forever } while(true) { // do this forever }
You can break out of a loop with a break or return. The return statement should only be used when the loop is contained in a called function body. You can call the next iteration prematurely with a continue statement.
That statement about enclosing code in braces sometimes elicits arguments from developers who routinely prefer to omit braces when the code block consists of a single line.
However, I stand by the assertion that putting in the braces tends to result in fewer misunderstandings when another programmer is maintaining your source. On the whole I can see no advantages in leaving out the enclosing braces even when the code block is a single line. It helps to remind you that the code is part of an iteration or condition and allows you to add a second line without worrying about the braces.
In a rush to add a second line, you might very easily omit the braces. That would cause the added line to be executed outside of the iteration loop or whether the condition matched or not. Because of the way people indent braces it is hard to spot when this has happened.
See also: | break, continue, for( ... ) ..., for( ... in ... ) ..., return, Statement, while( ... ) ... |
ECMA 262 edition 2 - section - 12.6
ECMA 262 edition 3 - section - 12.6
Wrox Instant JavaScript - page - 25
Prev | Home | Next |
isXDigit() | Up | J |
JavaScript Programmer's Reference, Cliff Wootton Wrox Press (www.wrox.com) Join the Wrox JavaScript forum at p2p.wrox.com Please report problems to support@wrox.com © 2001 Wrox Press. All Rights Reserved. Terms and conditions. |