Finders Keepers: Help with challenge

Finders Keepers: Help with challenge
0.0 0

#1

Tell us what’s happening:
It’s returning the undefined case, but not any numbers from the array.

Your code so far


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


#2

That is because your for loop only makes it one iteration before you return something. You only should return undefined if no element passes the test. Your function returns undefined if the very first element does not pass the test. Remember, when the return statement is executed, the function is exited and does not come back.


#3

Yup, that would be it. I should have stuck with the initial return FCC had. Thanks.


#4
function findElement(arr, func) {

  for(let i=0;i<arr.length;i++){

    if(func(arr[i]))
      return arr[i];
  }

  return undefined;
}