I was wondering why i get an error here - i know that by omitting === true and else I get the answer but I’d like to understand the logic behind that.
Thanks from Belgium
findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; }) should return 8.
Passed
findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; }) should return undefined.
function findElement(arr, func) {
let num = 0;
for (var i = 0; i < arr.length; i++) {
num = arr[i];
if (func(num) === true) {
return num;
}
else {
return undefined;
}
}
}
Your code reads as following: If the function returns true return my number, else return undefined. The problem is that if the first comparison func(num) === true fails, the else branch is executed and your code returns undefined, so you don’t traverse the whole array, you stop at the first element.
The correct code below:
You should move the return from the else branch outside the for loop, so if you don’t find a case that passes in the whole array, return undefined
function findElement(arr, func) {
let num;
for (var i = 0; i < arr.length; i++) {
num = arr[i];
if (func(num) === true) {
return num;
}
}
return undefined;
}