Why is my find method returning undefined?
I have recreated a number of Underscore.js methods for learning JavaScript and programming in general.
Below are my attempts to recreate the Underscore method _.find()
.
var find = function(list, predicate) { // Functional style
_.each(list, function(elem){
if (predicate(elem)) {
return elem;
}
});
};
var find = function(list, predicate) { // Explicit style
if (Array.isArray(list)) {
for (var i = 0; i < list.length; i++) {
if (predicate(list[i])) {
return list[i];
}
}
} else {
for (var key in list) {
if (predicate(list[key])) {
return list[key];
}
}
}
};
My second method find
which uses a loop for
and a loop for in
. Whereas my first method find
returns undefined
. I believe both should be doing the same job. However, they don't. Anyone please point out what's going on?
source to share
Yours return
only returns from an inner (nested) function, and your function find
doesn't really return anything hence undefined
.
Try this instead:
var find = function(list, predicate) { // Functional style
var ret;
_.each(list, function(elem){
if (!ret && predicate(elem)) {
return ret = elem;
}
});
return ret;
};
source to share