Please explain why does my solution not work

Hello! I am doing the ‘Finders Keepers’ basic algorithm scripting challenge.
Why does my solution not work, but this other one does?

My solution :

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

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

Working solution:

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

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

Thanks in advance for your assistance!

function findElement(arr, func) {
  let num = 0;
  for (let i = 0; i < arr.length-1; i++) {
    num = arr[i]
    if (func(num) === true) {
      // This return immediately stops function execution
      return num;
    } else {
      // This return immediately stops function execution
      return undefined
    }
  }
}

Remember that return immediately stops your function.

Side question: why are you only going up to arr.length - 1?

1 Like

Isn’t that what I would want? I want the function to stop executing once it’s found a value that passes the test, and then return that value?

I used arr.length-1 because that’s the value of the last index in the array.

You are stopping if you found a value and if you didn’t. The first value either matches or it doesn’t, so you only ever check the first.

length-1 is the last value, but i < means you never reach it.

1 Like

Oh okay gothca, meant to put i<=arr.length-1

Thanks for your help!

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