How to use the break statement to come out of a 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>

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 08-Jan-2020

94 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements