I’m trying to make a function that checks whether any element of an array satisfies its conditions. The below code doesn’t work, and it only returns undefined.
function findElement(arr, func) {
for (let i = 0; i < arr.length; i++) {
if (func(arr[i]) == true) {
return arr[i];
} else{
return undefined;
}
}
}
The code below this works properly.
function findElement(arr, func) {
for (let i = 0; i < arr.length; i++) {
if (func(arr[i]) == true) {
return arr[i];
}
}
return undefined;
}
Why can I not put else {return undefined}? I don’t understand why the first code doesn’t work and the second does.