Why does the first function work and second doesn't?

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

Returning from a callback doesn’t return from the outer function.

1 Like

forEach returns undefined anyway.

I would suggest you read the docs for the method as it has information about its usage and what not to use it for.


Also, just an FYI the find method already exists, if it’s just the functionality you need.

const array = [42, true, 'Something', null];
console.log(array.find(ele => ele === 'Something')); // Something
1 Like

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