Skip to main content

For Loop

Although while() is the simplest of the JavaScript loops, the most common type by far is the for() loop. This is slightly surprising when you consider (as you will shortly) that the for() loop's syntax is a bit more complex than that of the while() loop. However, the for() loop excels at one thing: looping when you know exactly how many times you want to repeat a group of statements. This is extremely common in all types of programming, so it's no wonder for() is so often seen in scripts. The structure of a for() loop looks like this:

 
for (var Counter = start; Counter_Expression; Counter++) { 
    statements
}
 
Counter A numeric variable used as a loop counter, ie: a number that counts how many times the procedure has gone through the loop. (Yu only need to include var if this is the first time you've used the variable in the script.)
start The initial value of Counter. This is usually 1, but you can use whatever value you need.
Counter_Expression A comparison or logical expression that determines the number of times through the loop. This expression usually compares the current value of Counter to some maximum value.
Counter++ The increment operator applied to the Counter variable. This can be any expression that changes the value of Counter.
statements The statements to execute each time through the loop.


When JavaScript sees the for() statement, it follows this seven-step process:

  1. Set Counter equal to start.
  2. Evaluate the Counter_Expression in the for() statement.
  3. If Counter_Expression is true, continue with step 4; if Counter_Expression is false, skip to step 7.
  4. Execute each of the statements in the block.
  5. Increment Counter.
  6. Return to step 2.
  7. Exit the loop (that is, execute the next statement that occurs after the for() block).

Next: Do while