Loops in Javascript
Loops in JavaScript
The types of loops in javascript are:
- for loop
- while loop
- do-while loop
For Loop
Iterates the elements for a fixed number of times. It should be used if a number of iterations are known.
<script type="text/javascript">
var count;
for (count=0; count < 5 ; count++){
document.write("Current Count:"+ count);
document.write("<br/>");
}
</script>
Output
Current Count: 0
Current Count: 1
Current Count :2
Current Count: 3
Current Count: 4
While Loop
Iterates the elements for an infinite number of times. It is mainly used if number of iterations is not known.
<script type="text/javascript">
var count=0;
while (count < 5){
document.write("Current Count:"+ count+ "<br/>");
count++;
}
</script>
Output
Current Count: 0
Current Count: 1
Current Count: 2
Current Count: 3
Current Count: 4
Do while Loop
It is similar to while loop except that the condition check happens at the end of the loop.
<script type="text/javascript">
var count=0;
do{
document.write("Current Count:"+ count+"<br/>");
count++;
}while (count < 0);
document.write("Loop stopped");
</script>
Output
Current Count: 0
Loop Stopped