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?