Tuesday, March 18, 2014

JavaScript while Loops

While writing a program, there may be a situation when you need to perform some action over and over again. In such situation you would need to write loop statements to reduce the number of lines.
JavaScript supports all the necessary loops to help you on all steps of programming.

The while Loop

The most basic loop in JavaScript is the while loop which would be discussed in this tutorial.

Syntax:

while (expression){
   Statement(s) to be executed if expression is true
}
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:

Following example illustrates a basic while loop:
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br />");
while (count < 10){
  document.write("Current Count : " + count + "<br />");
  count++;
}
document.write("Loop stopped!");
//-->
</script>
This will produce following result:
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped! 

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);
Note the semicolon used at the end of the do...while loop.

Example:

Let us write above example in terms of do...while loop.
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br />");
do{
  document.write("Current Count : " + count + "<br />");
  count++;
}while (count < 0);
document.write("Loop stopped!");
//-->
</script>
This will produce following result:
Starting Loop
Current Count : 0
Loop stopped! 

No comments:

Post a Comment