i2tutorials

Javascript-Break

Javascript-Break

 

In javascript break statement terminates the current loop(for, for … in, while, do … while), switch, or label statement and transfers program control to the statement following the terminated statement.

 

flow chart of a break statement :

 

Javascript-Break

 

Syntax:

 

break [label];

 

Working of JavaScript break Statement:

 

 

Example:

 

<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
        }
        x = x + 1;
        document.write( x + "<br />");
       }

       document.write("Exiting the loop!<br /> ");
       //-->
   </script>
 </body>
</html>

 

OUTPUT:

 

Entering the loop

2

3

4

5

Exiting the loop!

 

Labels to Control the Flow:

 

The break statement with a label recommendation, to “jump out” of a nested for loop. The labeled break is rarely used in JavaScript because this makes the code harder to read and understand.

 

Example:

 

<html>
 <body>

  <script type = "text/javascript">
    <!--
     document.write("Entering the loop!<br /> ");
     outerloop:        // This is the label name

     for (var i = 0; i < 5; i++)
     {
       document.write("Outerloop: " + i + "<br />");
      innerloop:
       for (var j = 0; j < 5; j++)
       {
         if (j > 3 ) break ;           // Quit the innermost loop
         if (i == 2) break innerloop;  // Do the same thing
         if (i == 4) break outerloop;  // Quit the outer loop
         document.write("Innerloop: " + j + " <br />");
        }
       }

       document.write("Exiting the loop!<br /> ");
     //-->
   </script>

 </body>
</html>

 

OUTPUT:

 

Entering the loop!

Outerloop: 0

Innerloop: 0

Innerloop: 1

Innerloop: 2

Innerloop: 3

Outerloop: 1

Innerloop: 0

Innerloop: 1

Innerloop: 2

Innerloop: 3

Outerloop: 2

Outerloop: 3

Innerloop: 0

Innerloop: 1

Innerloop: 2

Innerloop: 3

Outerloop: 4

Exiting the loop!

 

 

 

 

Exit mobile version