for Loops

A for loop combines the best of all worlds into a single looping construct that allows you to pass three parameters for each statement:

• An initialization expression
• A condition expression
• A modification expression

These are separated by semicolons, like this: for (expr1; expr2; expr3). At the start of the first iteration of the loop, the initialization expression is executed. In the case of the code for the multiplication table for 7, count would be initialized to the value 1. Then, each time round the loop, the condition expression (in this case count <= 7) is tested, and the loop is entered only if the condition is true. Finally, at the end of each iteration, the modification expression is executed. In the case of the multiplication table for 7, the variable count is incremented. Following Example shows what the code would look like.

for (count = 1 ; count <= 7 ; ++count)
document.write(count + "times 7 is " + count * 7 + "<br />");

As in PHP, you can assign multiple variables in the first parameter of a for loop by separating them with a comma, like this:

for (i = 1, j = 1 ; i < 10 ; i++)

Likewise, you can perform multiple modifications in the last parameter, like this:

for (i = 1 ; i < 10 ; i++, --j)

Or you can do both at the same time:

for (i = 1, j = 1 ; i < 10 ; i++, --j)

You may also like...