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
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.
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