When writing a program, there may be a situation when you need to perform some actions over and over again. In such cases, you need to write a looping statement to reduce the number of code.
JavaScript supports all the necessary loops to help you in all programming steps.
While Loop
The most basic loop in JavaScript is the while loop, which is discussed in this tutorial.
Grammar
while (expression) {
Statement (s) to was executed if expression is true
}
The while loop is intended to repeatedly execute a statement or block of code (as long as the expression is true). Once an expression is false, the loop is exited.
Example:
The following example illustrates a basic while loop:
<script type= "Text/javascript" >
<!--
var count = 0;
document.write ("Starting Loop" + "<br/>");
while (Count < ten) {
document.write ("Current count:" + count + "<br/>");
count++;
}
document.write ("Loop stopped!");
-->
</script>
This will produce the following results:
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!
Do...while Cycle:
The Do...while loop is similar to a while loop, except that the conditional check occurs at the end of the loop. This means that the loop will always execute at least once, even if the condition is false.
Grammar
do{
Statement (s) to is executed while
(expression);
Notice that a semicolon is used at the end of the do ... while loop.
Example:
As in the above example, write a use do ... while loop program.
<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 the following results:
Starting loop current
count:0
loop stopped!