Why is there no forEach loop in javascript?

The compiler threw me an 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?

+4
source share
4 answers

forEachmay make you believe that you are in the context of a cycle for, but it’s not.

This is just a method that runs for each of the elements in the array. Thus, inside the function you can control only the current iteration, but in no way can you cancel or break out of the method subscription for other elements of the array.

+7
source

An explanation of your question was well given by @Wim Hollebrandse.

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

['a', 'b', 'c'].some(function (x) {
  if (x == 'b') {
    return true; 
  }
});
+1

This is because you are in function. Keyword breaknot available here (out of loop)

0
source

Because it is a method in the Array prototype.

To exit, throw an exception.

0
source

Source: https://habr.com/ru/post/1620591/


All Articles