Finders Keepers: Return undefined outside the for loop

Tell us what’s happening:
Actually, I have seen the model answer. But I don’t know why “return undefined” should be written outside of the for loop. Just like below:

function findElement(arr, func) {
  let num = 0;
  for(var i = 0; i < arr.length; i++) {
    num = arr[i];
    if (func(num)) {
      return num;
    }
  }
  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])){
      num = arr[i];
      return num;
    }
    return undefined;
  }
}

Hm, without knowing what is the purpose of the Finders Keepers algorithm and blindly use the algorithm, i can only say that the return outside the loop prevents the return of “n” undefined.

So if it finds an element, then it returns that element, else the loop is executed and since it didn’t enter the if, the only return will be the undefined, but then again, i need to test it.

@siuhangw, the answer to your question is in the challenge description:

If no element passes the test, return undefined.

In the code where return undefined is in the loop, it’ll return undefined for the first array item that is false even though there may be other items in the array that are true.

In the code where return undefined is out of the loop, it’ll return the first array item that is true and if no array items are true after looping through all of them, it’ll return undefined.