Finders Keepers 0

Finders Keepers 0
0

#1

Tell us what’s happening:
How does this code work?

Your code so far


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

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/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

Let me respond by asking two questions:

1.) Where do you think the parameter function is being called in the code to determine if the element number is equal to zero?

2.) Why is the for loop stopping after the condition is met and then the num value is returned?


#3

The parameter function is being called in the if statement and the for loop stops because there is the break keyword, so it only loops once.

The num value is returned because otherwise it would remain a variable and not a result.

Is it right?


#4

Very good.

One suggestion though. In this instance, there is no need to break the for loop when you have a true statement. You can easily use a return statement instead of forcing a break on the for loop.