Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Return" out of Function, If Statement Inside Lodash forEach()

function(){
    _.forEach(listOfSomething, function (something) {
      if(someCondition){
        return false
      }
    });
    return true;
}

Looks simple enough - trying to check each item for some condition, if it isn't met for any item exit out of function and return false. When loop is done without exiting, return true.

Always returns true, tried console logging, and it does hit the "return false" point.

Am I missing something obvious about how js works or is this a lodash thing?

like image 327
VSO Avatar asked Oct 23 '15 21:10

VSO


People also ask

How do you break out of Lodash forEach?

Javascript. Conclusion: Hence to break Lodash forEach loop we have to return false from the callback function.

Can you return out of a forEach?

You can't make JavaScript's forEach() function return a custom value. Using return in a forEach() is equivalent to a continue in a conventional loop.

How do you break a forEach loop?

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.

What does forEach method return?

forEach() executes the callbackFn function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable.


2 Answers

What you're missing is that your return false statement is inside a different function than your return true statement. You probably want to use a different lodash method like any/some.

function(){
    return _.some(listOfSomething, function (something) {
      return someCondition;
    });
}
like image 200
StriplingWarrior Avatar answered Dec 27 '22 07:12

StriplingWarrior


Thats because there are 2 functions, the return of the second function won't make the first function return. You should set a variable as true and change it to false if the condition is met:

function(){
    var condition = true;
    _.forEach(listOfSomething, function (something) {
      if(someCondition){
        condition = false;
        return;
      }
    });
    return condition;
}
like image 29
taxicala Avatar answered Dec 27 '22 08:12

taxicala