8

I am trying to break out of an inner foreach loop using JavaScript/jQuery.

result.history.forEach(function(item) {
    loop2:
    item.forEach(function(innerItem) {
        console.log(innerItem);
        break loop2;
    });
}); 

This is resulting in the error 'Unidentified label loop2'. it appears to be right before the loop which was what other questions were saying was the issue.

What am I doing wrong and how do I fix it?

Edit: Correct, the foreach loop cant break in this way but a regular for loop can. This is working:

                        result.history.forEach(function(item) {
                            loop2:
                            for (var i = 0; i < item.length; i++) {
                                var innerItem = item[i];
                                console.log(innerItem);
                                break loop2;
                            }
                        });
David Tunnell
  • 7,252
  • 20
  • 66
  • 124

2 Answers2

8

If you need to be able to break an iteration, use .every() instead of .forEach():

someArray.every(function(element) {
  if (timeToStop(element)) // or whatever
    return false;
  // do stuff
  // ...
  return true; // keep iterating
});

You could flip the true/false logic and use .some() instead; same basic idea.

Pointy
  • 405,095
  • 59
  • 585
  • 614
5

Can't do it. According to MDN:

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behaviour, the .forEach() method is the wrong tool, use a plain loop instead. If you are testing the array elements for a predicate and need a boolean return value, you can use every() or some() instead.

Josh Beam
  • 19,292
  • 3
  • 45
  • 68
  • 1
    You can't break a `forEach` loop, but you can always use `.some()` or `.every()` instead. – Pointy Dec 22 '15 at 23:02