Finders Keepers Return Undefined!

Tell us what’s happening:
I passed the challenge, but I don’t understand why it is wrong when I return undefined inside of the loop in the if else statement. Like so:

Your code so far


function findElement(arr, func) {
  let num = 0;

  for (let i = 0; i < arr.length; i++) {
    if (func(arr[i]) == true) {
      return num = arr[i]
    } else {
      return undefined;
    }
  }
}

findElement([1, 2, 3, 4], num => num % 2 === 0);

**The correct Solution should be:

function findElement(arr, func) {
let num = 0;

for (let i = 0; i < arr.length; i++) {
if (func(arr[i]) == true) {
return num = arr[i]
}
}
return undefined;
}

findElement([1, 2, 3, 4], num => num % 2 === 0);

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/finders-keepers

Remember that a return statement exits the function. In your code above, a value is always returned in the first loop iteration.

Oh WOW, thank you! idk why the return statement is so tricky for me sometimes.

Another tip that could be useful is that since “func(arr[i])” returns a boolean value, then you could shorten the condition of the if statement to just say “if (func( arr[ i ] ))”. It does the same job, but with a little less code.

1 Like

Yes in majority of cases return would terminate loop construct, but there are exceptions such as forEach loop which will not exit if you try to terminate it by using return. Only way to terminate forEach is to throw and exception…

1 Like

The reason return doesn’t terminate a forEach is because forEach takes a callback function, so the return there is returning from the callback. The same thing applies to .map and .filter. The return statement isn’t behaving any differently, it’s just returning from the callback function.

2 Likes