Reputation: 6405
I know that this behaviour is well known and well documented: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, 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. If available, the new methods find() or findIndex() can be used for early termination upon true predicates as well.
var theSecond = findTheSecond()
console.log('theSecond is: ' + theSecond)
function findTheSecond(){
[1,2,3].forEach(function(e1) {
console.log('Item:' + e1)
if(e1 === 2) {
return(e1)
}
});
}
My question is why was JavaScript designed like this? Was this an oversight or a deliberate design decision for the language?
Upvotes: 0
Views: 833
Reputation: 1242
These functional iterator methods don't "break" like normal "for" loops probably because when you want to do "forEach" they probably were thinking you intentionally want to do something "for each" value in the array. To do what you want to do there as in "finding" the correct item, you can use "find"
var theSecond = findTheSecond();
console.log('theSecond is: ' + theSecond)
function findTheSecond(){
return (
[1,2,3].find(function(e1) {
console.log('Item: ', e1);
return e1 === 2
})
)
}
Forget the "for loop" which is imperative, get "functional"! There's plenty of methods on the array to choose from i.e. map, reduce, etc.
Upvotes: 2
Reputation: 386620
You could use Array#some
with a short cut, if necessary.
var theSecond = findTheSecond();
console.log('theSecond is: ' + theSecond);
function findTheSecond() {
var result;
[1, 2, 3].some(function (el, i) {
console.log('Item:' + el);
if (i === 1) {
result = el;
return true;
}
});
return result;
}
Upvotes: 0