Finders Keepers: undefined statement in the if statement?

Tell us what’s happening:
Why the return statement doesn’t do the same if nested as an else exit? Like the following code:

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

Your code so far


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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36 OPR/63.0.3368.75.

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

For the first code, the moment your loop (for) finds a number that does not return true it will return undefined making the first set of tests to fail on the challenge (the loop stops on the first value, never reaches the 8 that would make it return properly).

For the second, the return is outside the loop meaning that you first went through all of the loop and, if nothing was returned inside the loop (a return happens on the first tests when it reaches the 8 but not on the second set of tests since nothing matches) then it will reach your return undefined

Side note - in JS a function will return undefined by default if nothing is returned so for your second example you can even remove that return undefined and it will work

1 Like

Really well explained!. Thank you.

1 Like