-1

... more specefically, is it possible to break out of a forEach loop. In the code below the return statement in the if statement appears to do nothing.

This is because it is retuning to the callback function.

Here is a reference:

msdn - forEach

// underscore equivalent "cornerstone" fails b.c. of storage duality
var newForEach = function (obj, func, con) {
    if (Pub.isType("Function", func)) {
        Object.keys(obj).forEach(function (key) {
            if (func.call(con, obj[key], key, obj)) {
                return true;
            }
        });
    }
};

Note, I'm not interested in using another method. I'm curious as to where the return value goes.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
brannon
  • 1
  • 2

2 Answers2

0

The return value goes nowhere.

If you want to break out a forEach, then use some instead. It breaks when you return a truthy value.

Taken from the MDN documentation on 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.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • Of course, if you're actually doing something for each element in an array and want to break out early, you *are* allowed to just use a `for` loop with `break`. That's still part of the language... – Heretic Monkey Dec 07 '16 at 19:55
0

You can break out of the loop, but the return value is unused.

Since forEach doesn't return anything itself, it wouldn't make much sense to collect return values from the callback.

To break out, you need to throw during the callback:

var newForEach = function (obj, func, con) {
    if (Pub.isType("Function", func)) {
        Object.keys(obj).forEach(function (key) {
            if (func.call(con, obj[key], key, obj)) {
                throw new Error('something terrible happened!');
            }
        });
    }
};

However, that looks like exceptions as flow control, which is a Very Bad Thing. If that is what you're doing, there are probably other array methods that will be more helpful: perhaps every or filter.

ssube
  • 47,010
  • 7
  • 103
  • 140
  • 1
    What does `Array.prototype.forEach` actually return ... looks like undefined according to the docs ... – brannon Dec 07 '16 at 20:00