Finders Keepers Return 1 or more elements of array?

Finders Keepers Return 1 or more elements of array?
0

#1

Hello,
Do you have any idea for how my code can return 8 and not 10? My loop finish at 10, how can I have 8?
Thnx a lot for help.

function findElement(arr, func) {
  let num = 0;

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

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

Your browser information:

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

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


#2

The challenge expects your function to return the first element in the array in which the function passed in results in true. Your function will always return the last element of the array.

Why?

  1. You are not actually executing the function named func inside your array, so your if statement checks if func evaluates to true. Since functions are objects and all objects are “truthy” in Boolean terms, your if statement always evaluates to true and you keep assigning the current element in the array iteration to the num variable.

  2. Even if you figure out how to solve #1 above, you need to stop at the first time the function returns a true value and return that element.