Finders Keepers: Help with challenge

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/

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.

1 Like

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

function findElement(arr, func) {

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

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

  return undefined;
}

Thanks for the explanation RandellDawson

Can anyone please explain me the second parameter (num => num % 2 === 0)? I really don’t get this way of calling the method.

Isn’t there an easier way of calling it?

the function findElement is defined with two parameters, arr and func
instructions tell you that the first will always be an array and the second will always be a function

this is a function call:

the function is called with some arguments.
the first one is an array, [1, 2, 3, 4], the second one is a function, num => num % 2 === 0

is the function your issue? that function is defined using arrow function, a short hand introduced in ES6

2 Likes

I wonder if it’s possible to declare the function to pass as an argument in a more long-winded way. Is it possible?

these are also valid ways:

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

---

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

---

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

---

let func = function (num) {return num % 2 === 0};
findElement([1, 2, 3, 4], func);

---

function func (num) {return num%2 === 0}
findElement([1, 2, 3, 4], func);
1 Like

Thank you for replying ieahleen, now it’s definitely clearer :slightly_smiling_face: