Finders Keepers and ternary evaluations

Finders Keepers and ternary evaluations
0

#1

I already figured out the challenge using a for loop, but I was trying to shorten my code and use ternary evaluations, this is what i have but its not working.

return arr.forEach(func) == true ? arr.indexOf(arr.forEach(func)) : undefined;

It’s not working correctly tho, any takers?

The original code without my solution:

function findElement(arr, func) {
let num = 0;
return num;
}

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

FYI - arr.forEach(func) will always be undefined, because the forEach method does not return a value and functions which do not explicitly return values, return the value undefined. This means the first condition of:

 arr.forEach(func) == true

will evaluate to false, so your ternary will always yield undefined.


#3

ok, thanks, but is there a way to do this??

arr.forEach(func(arr at the current index) == true ? value at the index that passed :undefined;

Can I get the current index and run it through that function and then return that the value at that index using forEach?


#4

This is not a good place for a ternary in my opinion.