How to break a loop in JavaScript?

JavascriptWeb DevelopmentFront End Technology

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
raja
Published on 22-Jan-2018 17:53:54
Advertisements