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?


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.


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.