Skip to content Skip to sidebar Skip to footer

Where Does The Return Value Go For A Foreach Callback?

... 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 retun

Solution 1:

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)) {
                thrownewError('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.

Solution 2:

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.

Post a Comment for "Where Does The Return Value Go For A Foreach Callback?"