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>
  
Click to view the demo

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>
  
Click to view the demo

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>
  
Click to view the demo

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>
  
Click to view the demo
Home 
  JavaScript Book 
    Language Basics  

Statements:
  1. The if Statement
  2. The do...while Statement
  3. The while Statement
  4. The for Statement
  5. The for-in Statement
  6. Labeled Statements
  7. The break and continue Statements
  8. The with Statement
  9. The switch Statement