Skip to content

JavaScript forEach break | Exit loop example code

  • by

There is no way to stop or break a forEach() loop other than by throwing an exception in JavaScript. Use a simple loop instead.

JavaScript forEach break example

Simple example code interrupts execution you would have to throw an exception of some sort.

<!DOCTYPE html>
<html>
<head>

  <script>
    var BreakException = {};
    let arr = [1, 2, 3];

    try {
      arr.forEach(function(el) {
        console.log(el);
        if (el === 2) throw BreakException;
      });
    } catch (e) {
      console.log("BreakException")
      if (e !== BreakException) throw e;
    }
  </script>

</head>
<body>

</body>
</html>

Output:

JavaScript foreach break

JavaScript exceptions aren’t terribly pretty. A traditional for loop might be more appropriate if you really need to break inside it.

Use Array#some

Instead, use Array#some:

[1, 2, 3].some(function(el) {
  console.log(el);
  return el === 2;
});

This works because some returns true as soon as any of the callbacks, executed in array order, return true, short-circuiting the execution of the rest.

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this JS forEach topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *