0

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?

2
  • 2
    It certainly is deliberate design decision... There are other methods of array to handle otherwise scenarios... Commented Sep 14, 2016 at 5:41
  • Because it is forEach not forEachUntilStopped. Commented Sep 14, 2016 at 5:50

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I am going to reason about this based on your imperative/functional comment, which makes sense to me. Thanks for your answer.
0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.