While loop statements in Javascript

Using while statements

The while loop statement

  • A while loop statement has the form:
    while (expression) {
        statement;
    }
  • In a "while" loop, any statements that form the body of the loop is executed as long as the expression evaluates to true.
    <script type="text/javascript">
    var count = 0;             // initialize the condition
      while(count < 5) {       // test condition still true
        count++;               // body of the loop starts
        document.write("count: "+count+"<br>");
      }
      document.write("At end Count: "+count+"<br>");
    </script>

The do while loop statement

  • A do while loop statement has the form:
    do {
        statement;
    } while (expression);
  • In a "do while" loop, all the statements that form the body of the loop is executed once before the evaluation of the expression. Otherwise, this loop works the same way that "while" loop.
    <script type="text/javascript">
      var count = 0;           // initialize the condition
      do {
        count++;               // body of the loop starts
        document.write("count: "+count+"<br>");
      } while(count<5)         // test condition still true
      document.write("At end Count: "+count+"<br>");
    </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.