Break Statement in JavaScript

The break statement terminates the current loop and transfers the control out of the loop.

The break statement can also be used to jump out of a loop.

The break statement breaks the loop and continues executing the code after the loop. The break statement, without a label reference, can only be used to jump out of a loop or a switch.

The break statement exits a switch statement or a loop (for, for … in, while, do … while).

When the break statement is used with a switch statement, it breaks out of the switch block. This will stop the execution of more execution of code and/or case testing inside the block.

Example

The following example illustrates the use of a break statement with a while loop. Notice how the loop breaks out early once x reaches 5 and reaches to document.write (..) statement just below to the closing curly brace.

<html>
   <body>

      <h1>JavaScript Break Statement</h1>

      <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>


   <br/><br/>
   <p>Powered by easycode.onewebapp.com</p>
</html>

 

Output

JavaScript - Break Statement