for

The for statement provides a looping construct that is often more convenient than the while statement. The for statement takes advantage of a pattern common to most loops (including the earlier while loop example). Most loops have a counter variable of some kind. This variable is initialized before the loop starts and is tested as part of the expression evaluated before each iteration of the loop. Finally, the counter variable is incremented or otherwise updated at the end of the loop body, just before expression is evaluated again.

The initialization, the test, and the update are the three crucial manipulations of a loop variable; the for statement makes these three steps an explicit part of the loop syntax. This makes it especially easy to understand what a for loop is doing and prevents mistakes such as forgetting to initialize or increment the loop variable. The syntax of the for statement is:

for(initialize ; test ; increment)
    statement

The simplest way to explain what this for loop does is to show the equivalent while loop:[20]

               initialize;
while(test) {
    statement
               increment;
}

In other words, the initialize expression is evaluated once, before the loop begins. To be useful, this is an expression with side effects (usually an assignment). JavaScript also allows initialize to be a var variable declaration statement, so that you can declare and initialize a loop counter at the same time. The test expression is evaluated before each iteration and controls whether the body ...

Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.