JS.10.5 Iteration Statements

A 'for' loop consists of three optional expressions, enclosed in parentheses and separated by semi-colons.

for([init-expression];[condition];[increment-expression]) {

  statements;

}

The initial-expression is evaluated before the loop starts. It is normally used to declare and initialize a counter variable. The condition statement is evaluated at the beginning of every loop. If the condition is true, the statements are executed. Otherwise, the loop terminates. The increment-expression is executed after the body statements. It is normally used to increment the counter variable.

for(var idx = 0; idx < array1.length; idx++) {

  ...

}

A special 'for' loop allows iteration through all properties of an object. If the object is an array, each item in the array is treated as a property.

var props = "";

for(var item in obj) {

  props += item + " = " + obj[item];

}

A 'while' statement is a loop with a single condition. The condition is evaluated at the beginning of every loop. If the condition is true, the body of the loop is executed. Otherwise, the loop is terminated.

while(condition) {

  statements;

}

A slight variation of the 'while' statement is 'do...while'. Instead of evaluating the condition at the beginning of the loop, 'do...while' statement evaluates the condition at the end of a loop. This guarantees the loop is at least executed once.

do {

  statements

} while(condition);

A loop can be terminated in the body by inserting a 'break' statement. A 'break' statement causes the execution to immediately transfer to the point following the end of the loop.

Similarly, a 'continue' statement interrupts the execution of a loop and transfer the execution to the end of the loop block.

<< JS.10.4 The 'try-catch' Statement © 1996-2013 InetSoft Technology Corporation (v11.5) JS.10.6 The 'switch' Statement >>