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?
Javascript. Conclusion: Hence to break Lodash forEach loop we have to return false from the callback function.
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.
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.
forEach() executes the callbackFn function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable.
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;
});
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With