Finders Keepers returns undefined

Finders Keepers returns undefined
0

#1

Tell us what’s happening:
Why is i undefined? The truth condition is satisfied and will log but I cannot get it to return. Not sure how the return here works.

Your code so far


function findElement(arr, func) {
  arr.forEach((i) => {
  	if(func(i)){
		return i
	}
   })
}


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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/finders-keepers


#2

forEach takes a callback function and according to the specification

forEach() executes the callback function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable.

I think since you want to find the first element that satisfies the condition you could try using a for loop and using ‘break’ to get out of the loop once the condition check is satisfied on a specific element.


#3

So that means you cannot return from forEach() at all? I should have looked this up. I’ll take a look at the forEach docs. Thx


#4

forEach does not explicitly return a value. It’s sole purpose is to iterate through the entire array it is called upon. There is a hack way to break out of forEach, but it looks messy and defeats the entire purpose of using the forEach. I suggest choosing a different approach.