# Basic Algorithim: Finders Keepers

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.

1 Like

Once you return, youâ€™re done, the function exits. The only way you could keep hold of the numbers is if you saved them to an array then returned that once the loop has finished.

2 Likes

Your code returns the first (truthy) number it finds in the array - 8, so it stops and doesnâ€™t get to 10.

And because return stops the code you donâ€™t get to return undefined. You would only return undefined if there was no even number in the array.

1 Like

Thank you. I didnâ€™t know return also exits the function. Makes sense now.

Dude, never return undefined.