Javascript for








for

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:


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; 
var i = 0; 
while (i < count){
   document.writeln(i); 
   i++; 
} 

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; ){
    console.log(i); 
    i++; 
} 

The code above generates the following result.

for-in

The for-in statement is used to enumerate the properties of an object. Here's the syntax:

for (property in expression) 
   statement

The for-in statement is used to display all the properties of the BOM window object.

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        for (var propName in window) { 
            document.writeln("<br/>"+propName); 
        } 
    </script>
</head>
<body>
</body>
</html>

The code above generates the following result.