Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't forEach a loop in javascript?

Tags:

javascript

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?

like image 918
Tân Avatar asked Feb 08 '23 06:02

Tân


1 Answers

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.

like image 167
Wim Avatar answered Feb 11 '23 01:02

Wim