The for Statement
for ([initial-expression]; [condition]; [increment-expression])
The initial-expression is typically a variable declaration, something like,
The condition is evaluated for each iteration. It can either return true or false. If it returns true, the statements inside the curly braces are performed. If it returns false, the statements in the curly braces are not performed. It can be something like,
This condition actually means, while i is less than 5.
The increment-expression is generally used to increment, the variable, i. You have something like this:
Let us now consider an example: The following code simply displays the iteration number (try the code and do not forget to click the OK button of the alert box to see the next number).
How and when to use the for…in Statement
The for…in statement is the same as the for statement but the condition and the increment-expression are replaced by an array or a container (see below). Let us look at an example first before we continue.
In the above code, you have an array. The first element of the array is ‘A’, the second is ‘B’, third is ‘C’, fourth is ‘D’ and fifth is ‘E’. There are 5 elements in the array, meaning we have 5 iterations like in the previous case. Array index counting begins from zero. So the iteration for the array is from zero to 4, just like in the previous case. So, instead of writing the condition and the increment-expression in the parentheses we simply write the array.
In the first code we have the initial-expression as “var i=0”. Now, this is actually the declaration of a variable, i and initialization of it. This variable is also a counter. It counted from zero to 4. In the second code, we declared the same variable for the same purpose, but did not initialize it. In the second code, the word “in” means that the variable is a counter (iterator) for the array.
The syntax for the for…in statement is then
for (var i in container)