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?
forEachnotforEachUntilStopped.