Loop control statements: There may be some situations when you have to come out of loop immediately without reaching at end or there may also be some situations that you need to skip one or two iterations within loop and move to the next iteration.
To handle such situations JavaScript provide break and continue loop control statements. By using these statements we can come out of loop at any point or skip any iteration and move on to next. These statements can properly understand with the help of following examples.
break statement: The break statement is used to break the loop immediately on the bases of any condition
<html> <body> <script type = "text/javascript"> var x = 1; document.write("Entering the loop<br /> "); while (x < 20) { if (x == 5) { break; // breaks out of loop completely } document.write( x + "<br />"); x = x + 1; } document.write("Exiting the loop!<br /> "); </script> </body> </html>
Output:
Entering the loop 1 2 3 4 Exiting the loop
Explanation:
- Initialize x = 1.
- while(x<20), loop will move until x is less than 20.
- Print each value of x , x will increment by 1 each time.
- if(x==5), when x will equals to 5 then loop will break and control will exit out from loop.
break statement can also use with switch-case statement.
continue statement: When the continue statement occurs in loop , it skip the whole remaining code and check the entering condition again. If the condition is still true then loop run for next iteration otherwise the control comes out of loop.
<html> <body> <script type = "text/javascript"> var x = 0; document.write("Entering the loop<br/ > "); while (x < 10) { x = x + 1; if (x == 5) { continue; // skip rest of the loop body } document.write( x + "<br />"); } document.write("Exiting the loop<br /> "); </script> <p> Value 5 is skipped!!!</p> </body> </html>
Output:
Entering the loop 1 2 3 4 6 7 8 9 10 Exiting the loop Value 5 is skipped!!!
Explanation:
- Initialize x=0.
- Loop will move till x is equal to 10.
- In each iteration x is incremented by 1.
- When x is equals to 5 , loop will exit with running print statement.