function findElement(arr, func) {
for (let i=0; i < arr.length; i++) {
let num = arr[i]
if(func(num)) {
return num
}
}
return undefined
}
findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; })
The above returns 8 for the given test case. However, this is very different from what I would have expected it to return. I thought it would return 8, 10, and undefined, in that order. My thought process: The for loop is first read, it iterates through every number in the array. If the number is even, the number is returned. Once it reaches 8, this is true for the callback function. It returns 8. But then I thought, well the for loop is not finished yet. It iterates to 10, which is also even so it should then also returns 10. Finally, the for loop has iterated through all items in the array. The “return undefined” code is outside of the for loop. So it then returns “undefined.” In fact because “return undefined” is outside of the for loop, it’s not contigent on a condition to run. Calling our findElement() function should return “undefined” regardless always.
I need help understanding why the function above returns just 8 and not 8,10, undefined?
Thanks.