0

The below function will always return true, because the return false; returns the function passed to forEach.

function exampleFunction(array){
    array.forEach(function(element){
        if(element.condition){
            return false; 
        }
    });
    return true;
}

Now, obviously the below works:

function exampleFunction(array){
    var result = true;
    array.forEach(function(element){
        if(element.condition){
            result = false; 
        }
    });
    return result;
}

but it's not ideal because it does unnecessary iterations. I know I could solve the problem by using a different loop to forEach, but I'm wondering if there's a way to do it keeping forEach. So, how can I return from the 'above' function in JavaScript when inside a nested function?

Jonah
  • 1,495
  • 4
  • 17
  • 32

3 Answers3

2

There's no way to break a .forEach loop during the loop other than throwing an exception (but don't do that). Use a for loop if you need to break mid-way. If you really need a method or a function:

function forEach(arr, func) {
    for (var i = 0; i < arr.length; i++) {
        if (func(arr[i], i) === false) {
            break;
        }
    }
}

// Or...
Array.prototype.softLoop = function(func) {
    for (var i = 0; i < this.length; i++) {
    ...
}

var my_array = [0, 1, 2, 3];
my_array.softLoop(function(element, index) {
    console.log(index, element);
    if (element == 2) {
        return false;
    }
});

You could even modify it so you didn't need a flag outside the loop:

Array.prototype.softLoopReturnable = function(func) {
    for (var ret, i = 0; i < this.length; i++) {
        ret = func(arr[i], i);
        if (ret === false) {
            break;
        }
    }
    return ret;
}
wilsonzlin
  • 2,154
  • 1
  • 12
  • 22
1

You could use Array.prototype.some:

function exampleFunction(array){
  return !array.some(function(element){
    return element.condition;
  });
}

In the code above, exampleFunction will return false when it comes across the first element where condition is truthy or true if none are found.

SimpleJ
  • 13,812
  • 13
  • 53
  • 93
0

You can short circuit the forEach by throwing an exception, but a better way would be to use Array.prototype.some():

function doesNotContainOnes(array){
    return !array.some(function(el) { return el === 1; });
}

document.body.innerHTML = doesNotContainOnes([5,9,6]) + '<br>'       // true
                        + doesNotContainOnes([5,9,6,'hi']) + '<br>'  // true
                        + doesNotContainOnes([5,9,6,1]) + '<br>';    // false
Community
  • 1
  • 1
blex
  • 24,941
  • 5
  • 39
  • 72