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>

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

    try {
      arr.forEach(function(el) {
        if (el === 2) throw BreakException;
    } catch (e) {
      if (e !== BreakException) throw e;




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) {
  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.


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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading