JavaScript Algorithms and Data Structures - Finders Keepers

This is my first answer of the question, and it shows me ‘undefined’. (It should be ‘2’)

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

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

The correct answer is this.

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

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

  return undefined;
}

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

I don’t understand why my code doesn’t work.
Can someone explain me please?

Your first if statement will immediately return undefined and break the loop/end the function if (func(num) === true) is false.

The second one works because the return undefined was moved out of the if statement and out of the loop, so it will only execute if the loop finishes without returning num

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.