forEach loop is not working

Tell us what’s happening:
In this challenge, for loop is working fine. But forEach loop is not. Why so?

Your code so far


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

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

Challenge: Finders Keepers

Link to the challenge:

You can not return a value from a forEach. The purpose of a forEach is to apply some function to every element of the array it is called on. Stick with a normal for loop.

1 Like

Thanks for reply.
MDN also says that the default return value is undefined. But it does not say why.

In that case conditional check is also not possible in forEach block, right?

Can you elaborate?

Yeah. That makes sense. Thanks a lot!