Loops are higly useful in javascript to iterate some action over and over until some specified conditions are met. Instead of writing a huge block of code, we can use loop to make the javascript do the work. Two types of loops are supported in javascript which are as follows.
for loop can be used when the number of iteration of a piece of code is known in advance.
<script> for (variable=startvalue; variable<=endvalue; variable=variable+incrementfactor){ // script goes here } </script>
<script> x = 0; for (x = 1; x <= 5; x++) { document.write("The number is:"+ x +"<br>"); } </script>
while loop is used when the number of iteration is not known in advance so we write the script in such a way that the iteration continues until a defined condition is met.
while (variable<=endvalue){ // script goes here }
<script> x = 1; while(x <= 5) { document.write("The number is: "+ x +"<br>"); x++; } </script>
break and continue are two special commands that can be used in a loop. break is used to break the iteration of the loop when certain condition is met. continue is used to break the iteration, perform some task and then continue the iteration again.
<script> i = 1; while (i <= 10){ if(i == 5){ document.write("FIVE <br>"); break; } document.write(i+"<br>"); i++; } </script>
<script> i = 1; while (i <= 10){ if(i == 5){ document.write("FIVE <br>"); i++; continue; } document.write(i+"<br>""); i++; } </script>
Leave a comment