User Rating: 2 / 5

Star ActiveStar ActiveStar InactiveStar InactiveStar Inactive
 

The While Loop

The purpose of a while loop is to execute a statement or code block repeatedly as long as expression is true. Once expression becomes false, the loop will be exited.

Example:

<html>
<body>
<script type="text/javascript">
var count = 0;
while (count < 5){
  document.write("Number : " + count + "<br />");
  count++;
}
</script>
</body>
</html>

This is the result:

 

The do...while Loop:

The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false.

Syntax:

do{
   Statement(s) to be executed;
} while (expression);

Example:

<html>
<body>
<script type="text/javascript">
var count = 0;
do{
  document.write("Number : " + count + "<br />");
  count++;
}while (count < 0);
</script>
</body>
</html>

This is the result:

 

 

Next

Chapter 16 - JavaScript Breaks