Basic Algorithm Scripting: Finders Keepers a Problem

Tell us what’s happening:

Hello, below is the solution i took from the guide and i want to understand why “return undefined” is not inside the for loop.
When i look at this code, it looks like it’s gonna return undefined irrespective of the for loop.

Secondly, how is the for loop returns only the first element that passes the test which is 2, but why not return 4 or both 2,4 as it iterates through the array?

Your code so far


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

}
console.log(findElement([1, 2, 3, 4], num => 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/78.0.3904.108 Safari/537.36.

Challenge: Finders Keepers

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

It might help you to log the value of num within the for loop

for (var i = 0; i < arr.length; i++) {
   num = arr[i];
   console.log(num);
   if (func(num)) {
     return num;
   }   
}

From this you can see that the function stops as soon as it returns a value. This is why undefined is not displayed if a match is found earlier, or why it displays only 2 and not 4 as well.

For more information, the MDN docs describe the return statement in details.

Hope it helps.

1 Like