Use Break Statement to Exit Loop in JavaScript



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>
Updated on: 2020-01-08T08:34:34+05:30

163 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements