Finders Keepers not passing

Finders Keepers not passing
0

#1

Tell us what’s happening:
Not sure why this isnt passing?

Your code so far


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

findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; })

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

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


#2

If the filter fails to find anything, you are returning the word “undefined”


#3

Ok, thanks Dan I fixed it, now it is passing all the tests. THank you!
However can you please explain to me the following:

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

console.log(findElement([1,4,2,3, 5, 9,7], function(num) { return num % 2 === 0; }));

The only difference in the above is I took num=arr[i]; and I placed it before the if statement. This will return the first even number however, if there are no even numbers it will still return the last number of the array regardless of if its even or odd. I realize this is incorrect, but can you please explain why does it do this?


#5

Can you please explain why it does this?


#6

On this line, you set num as the current value of the array.

    num=arr[i];

You then return out of the function if the filter works:

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

But then once the loop is finished, you always return num.

  return num;
}

So unless the filter function returns true, num is always the last value in the array.

Hint: you don’t need that num variable at all, you can just return arr[i] if the filter is true.