Tell us what’s happening:
Hello, below is the solution i took from the guide and i want to understand why “return undefined” is not inside the for loop.
When i look at this code, it looks like it’s gonna return undefined irrespective of the for loop.
Secondly, how is the for loop returns only the first element that passes the test which is 2, but why not return 4 or both 2,4 as it iterates through the array?
Your code so far
function findElement(arr, func) {
let num = 0;
for (var i = 0; i < arr.length; i++) {
num = arr[i];
if (func(num)) {
return num;
}
}
return undefined;
}
console.log(findElement([1, 2, 3, 4], num => num % 2 === 0));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36
.
Challenge: Finders Keepers
Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/finders-keepers