For loop statements in Javascript.

Using for statements

The ordinary for loop statement

  • A for loop statement has the form:
    for(initialize ; expression ; increment) {
        statement;
    }
  • A for loop combines the three steps of initializing, testing, and incrementing into one statement:
    <script type="text/javascript">
      var count = 0;             // initialize the condition
      // The initializing part is: count = 0  (when the loop starts)
      // The test part is     : count < 5 (if true ; execute the body statements)
      // The incrementing part is: count++  (executes for each loop)
      for (count = 0; count < 5; count++) {
        document.write("I got a hotdog !<br>");
      }
      document.write("At end Count: "+count+"<br>");
    </script>

The EMPTY for loop statement

  • You can have NO Statement in a for Loop, but the use of it is rare:
    <script type="text/javascript">
      for (var count = 0; count<5;
         document.write("count: "+ count++ +"<br>"));
      // There is no statement in the body of the for loop
      ; // This is an empty statement
    </script>

The enhanced for loop statement

  • A enhanced for loop (or for/in loop) statement has the form:
    for (variable in object) {
        statement;
    }
  • The for/in statement provides a way to loop through the properties of an object.
  • The body of the for/in loop is executed once for each property of object.
  • Before the body of the loop is executed, the name of one of the object's properties is assigned to variable.
    <script type="text/javascript">
      var verbs = ["composite ", "a ", "This ",
        "using ", "index!", "is ",
        "indirect ", "string "];
      var index = [2, 5, 1, 0, 7, 3, 6, 4];
    // verbs and index are arrays, which
    // both are a kind of an object in Javascript
      for (var i in index) {
       document.write(verbs[index[i]]);
      }
    </script>

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.