I've done quite a bit of reading and seen many different questions regarding this topic, but I was wondering if I could get help on WHY breaking out of a For Each loop doesn't work. Also, I am pretty new, so I apologize in advance if this question was answered in a different way that I wasn't able to understand.
So far, I have written a forEach function to emulate a native .forEach method:
function forEach(collection, callback){
if(collection.isArray){
for(var i =0;i<collection.length&&callback(collection[i])!==false;i++){
callback(collection[i]);
}
}else{
for(var key in collection){
callback(collection[key]);
}
}
}
When I try to utilize this to write another function 'find' that searches for the first instance of the array that matches a criteria, using 'return' or 'break' doesn't seem to work. find([1,2,3,4,5].function(x){return x>3;}); returns 5 instead of 4.
function find (collection, criteria){
var result;
forEach(collection, function(x){
if(criteria(x)){
result =x;
return false;
}
});
return result;
}
I have been able to recreate the effect that I want using other functions, but would like to understand why this doesn't work, as I am learning how to implement the use of functions within other functions.
Thank you.
returnanyway even if you leave out that word, by the way.