How to use the break statement to come out of a loop in JavaScript?

JavascriptWeb DevelopmentFront End Technology

The break statement is used to exit a loop early, breaking out of the enclosing curly braces.

Example

You can try to run the following code to learn how to use the break statement to come out of a loop

Live Demo

<html>
   <body>
      <script>
         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>
raja
Published on 23-Jan-2018 12:58:24
Advertisements