4

Compiler threw me error when I tried:

['a', 'b', 'c'].forEach(function (x) {
   if (x == 'b') {
      break //error message: Can't have 'break' outside of loop
   }
})

Valid syntax:

var x = ['a', 'b', 'c'];
for (var i = 0; i < x.length; i++) {
    if (x[i] == 'b') {
        break
    }
}

So, why?

Tân
  • 1
  • 15
  • 56
  • 102
  • 6
    Possible duplicate of [How to short circuit Array.forEach like calling break?](http://stackoverflow.com/questions/2641347/how-to-short-circuit-array-foreach-like-calling-break) – Koshinae Dec 17 '15 at 15:50

4 Answers4

7

The forEach may lead you to believe that you are inside the context of a for loop, but this is not the case.

It is simply a method that is executed for each of the elements in the array. So inside the function, you only have control over the current iteration but can in no way cancel or break out of the method subscription for the other array elements.

Wim
  • 11,998
  • 1
  • 34
  • 57
1

The explanation for your question was well given by @Wim Hollebrandse.

If you want to break the loop, try using some instead of forEach:

['a', 'b', 'c'].some(function (x) {
  if (x == 'b') {
    return true; 
  }
});
Yaron Schwimmer
  • 5,327
  • 5
  • 36
  • 59
0

That's because you are in a function. The break keyword is not available here (outside of a loop)

Ludovic Feltz
  • 11,416
  • 4
  • 47
  • 63
0

Because it's a method in the Array prototype.

To break out, throw an exception.

Koshinae
  • 2,240
  • 2
  • 30
  • 40