Hello! I am doing the ‘Finders Keepers’ basic algorithm scripting challenge.
Why does my solution not work, but this other one does?
My solution :
function findElement(arr, func) {
let num = 0;
for (let i = 0; i<arr.length-1; i++){
num = arr[i]
if(func(num) === true){
return num;
} else {return undefined}
}
}
findElement([1, 2, 3, 4], num => num % 2 === 0);
Working solution:
function findElement(arr, func) {
let num = 0;
for (let i = 0; i<arr.length-1; i++){
num = arr[i]
if(func(num) === true){
return num;
}
}
return undefined;
}
findElement([1, 2, 3, 4], num => num % 2 === 0);
function findElement(arr, func) {
let num = 0;
for (let i = 0; i < arr.length-1; i++) {
num = arr[i]
if (func(num) === true) {
// This return immediately stops function execution
return num;
} else {
// This return immediately stops function execution
return undefined
}
}
}
Remember that returnimmediately stops your function.
Side question: why are you only going up to arr.length - 1?