The for Statement
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;
}
And here's an example of its usage:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var count = 10;
for (var i=0; i < count; i++){
document.writeln(i);
}
//0 1 2 3 4 5 6 7 8 9
</script>
</head>
<body>
</body>
</html>
This for loop is the same as the following:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var count = 10;
var i = 0;
while (i < count){
document.writeln(i);
i++;
}
</script>
</head>
<body>
</body>
</html>
There are no block-level variables in JavaScript, so a variable defined inside the loop is accessible outside the loop.
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var count = 10;
for (var i=0; i < count; i++){
document.writeln(i);
}
document.writeln(i); //10
</script>
</head>
<body>
</body>
</html>
The initialization, control expression, and postloop expression are all optional.
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var count = 10;
var i = 0;
for (; i < count; ){
document.writeln(i);
i++;
}
</script>
</head>
<body>
</body>
</html>