Why the default value has to be set outside of the if

I’m trying to make a function that checks whether any element of an array satisfies its conditions. The below code doesn’t work, and it only returns undefined.

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

The code below this works properly.

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

Why can I not put else {return undefined}? I don’t understand why the first code doesn’t work and the second does.

Assume that arr has two elements, for first one func will return false, for second true. Consider what is returned by each of these functions in such case - try going step-by-step through the function.

2 Likes

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