How to break a loop in JavaScript?


The break statement is used to break a loop and continue executing the code, which is after the loop.

Example

You can try to run the following code to break a loop in JavaScript

Live Demo

<!DOCTYPE html>
<html>
   <body>
      <p id="test"></p>
      <script>
         var text = "";
         var i;

         for (i = 0; i < 5; i++) {
            if (i === 2) {
               break;
            }
            text += "Value: " + i + "<br>";
         }
         document.getElementById("test").innerHTML = text;
      </script>
   </body>

</html>

Output

Value: 0
Value: 1

Updated on: 08-Jan-2020

288 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements