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?

When a function does not explicitly return a value (in the case of the forEach method, the value undefined is returned.

You can still make conditional statements in the forEach loop. You can actually use a forEach loop to solve this challenge, but you will need two extra variables declared outside it:

  • a variable to act as a flag to tell you whether or not an element was found that caused the function to evaluate to true
  • a variable to capture the element’s value that caused the function to evaluate to true.

It is a bit more work and will not be as readable as using a regular for loop or for of loop.

1 Like

Yeah. That makes sense. Thanks a lot!