Loops Control Statements in JavaScript
Loop control statements deviates a loop from its normal flow. All the loop control statements are attached to some condition inside the loop.
break statement
break statement is used to break the loop on some condition.
Syntax
for(initializer, condition, modifier) { if(condition) { break; } statements; } //same thing is valid for while loop while(condition) { if(condition) { break; } statements; }
Example
<script> for(var i=1;i<10;i++) { if(i===7) break; document.write(i + "<br />"); } /**********output*********** 1 2 3 4 5 6 ***************************/ </script>
for loop should print from 1 - 10. But inside loop we have given a condition that if value of i equals to 7, then break out of loop. I have left the curly braces within the if condition because there is only one statement to be executed.
Remember break burst the nearest for loop within which it is contained. To understand what it means check out the next example.
Example
<script> for(var i=1;i<=3;i++) { document.write("Outer Loop : " + i + "<br />"); for(var j=1;j<=3;j++) { document.write("Inner Loop : " + j + "<br />"); if(j===2) { break; } } document.write("<br />"); } /**********output*********** Outer Loop : 1 Inner Loop : 1 Inner Loop : 2 Outer Loop : 2 Inner Loop : 1 Inner Loop : 2 Outer Loop : 3 Inner Loop : 1 Inner Loop : 2 ***************************/ </script>
continue statement
continue statement is used to skip an iteration of a loop.
Syntax
for(initializer, condition, modifier) { if(condition) { continue; } statements; } //same thing is valid for while loop while(condition) { if(condition) { continue; } statements; }
Example
<script> for(var i=0;i<10;i++) { if(i===3 || i===7) continue; document.write(i + "<br />"); } /**********output*********** 0 1 2 4 5 6 8 9 ***************************/ </script>
In the code above when the value of i becomes 3 or 7, continue forces the loop to skip without further executing any instructions inside the for loop in that current iteration.
Remember continue skips the nearest loop iteration within which it is contained. To understand what it means check out the next example.
Example
<script> for(var i=1;i<=3;i++) { document.write("Outer Loop : " + i + "<br />"); for(var j=1;j<=3;j++) { if(j===2) { continue; } document.write("Inner Loop : " + j + "<br />"); } document.write("<br />"); } /**********output*********** Outer Loop : 1 Inner Loop : 1 Inner Loop : 3 Outer Loop : 2 Inner Loop : 1 Inner Loop : 3 Outer Loop : 3 Inner Loop : 1 Inner Loop : 3 ***************************/ </script>
When value of j inside inner loop becomes 2, it skips that iteration.