How to create for loop in Javascript
Description
The for statement's syntax:
for (initialization; expression; post-loop-expression)
statement
A common implementation initializes a counting variable, i; increments the value of i by 1 each time; and repeats the loop until the value of i exceeds some maximum value:
for (var i = startValue;i <= maxValue;i++)
{
statements;
}
Example
And here's an example of its usage:
var count = 10;
for (var i=0; i < count; i++){
document.writeln(i);
}
The code above generates the following result.
This for loop is the same as the following:
var count = 10; //from w w w .ja va 2 s . c o m
var i = 0;
while (i < count){
document.writeln(i);
i++;
}
Note
There's no need to use the var
inside the for loop initialization.
var count = 10;
var i;
for (i=0; i < count; i++){
console.log(i);
}
There are no block-level variables in Javascript.
Example 2
The initialization, control expression, and postloop expression are all optional.
var count = 10;
var i = 0;
for (; i < count; ){// w w w . j ava 2 s.co m
console.log(i);
i++;
}
The code above generates the following result.