Finders Keepers. Need help with explanation

Finders Keepers. Need help with explanation
0

#1

Hi, does anyone here understand, why this code doesn’t work?

My code so far


function findElement(arr, func) {

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


}

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




Browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36 OPR/56.0.3051.52.

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


#2

Your for loop only makes a single iteration, before returning either a value or undefined. Why? Because when a return statement executes, the function immediately exits. Think about when you should really return undefined?


#3

Now it works! Thank you!