# Basic Algorithm Scripting: Finders Keepers *Trying to understand if statements*

I am a little bit confused about the Finders Keepers assignment.

I already understand that using `find()` is the most efficient way to solve this problem.

But, before I learned about `find()`, I was struggling to come up with a solution.

This is the solution I thought would work, but it doesn’t:

``````function findElement(arr, func) {
for (var i = 0; i < arr.length; i++) {
let num = arr[i];
func(num) === true ? num : undefined;
}
}
``````

From what I understand, I am testing if:

``````func(num) === true
``````

And if that test evaluates to be `true`, `num` would be returned.
Otherwise, `undefined` would be returned because the test evaluated to `false`.

But no matter which functions I pass through, the ternary operator seems to only return `undefined`.

I would greatly appreciate any insight into this problem!

You’re not returning anything anywhere, the function will always return undefined

3 Likes

Also, you don’t want to return `undefined` after the first `false` because you won’t go through any remaining elements in the array.

1 Like

LOL Well. That was a big oopsy. I appreciate that.

Ahh! I’m pretty sure I get it now.

So using a ternary operator wouldn’t be useful here, because it will stop the `for` loop from iterating through the rest of the array.

Yes, if you are going to use it as the return statement then it will always return on the very first element in the array. I’m not saying you can’t use a ternary operator in this solution, just not the way you are currently using it.

1 Like

So this is my new solution:

``````function findElement(arr, func) {
for (var i = 0; i < arr.length; i++) {
let num = arr[i];
if (func(num) === true) {
return num;
};
}
return undefined
}
``````

moving

``````return undefined
``````

outside of the `for` loop allows the iterations to continue through the array until the function evaluates to true.

1 Like

Also realized that since the functions being passed through `findElement` are boolean tests:

``````if (func(num) === true)
``````

Can be condensed to:

``````if(func(num))
``````

Now I understand how “Solution 1” was achieved! LOL

I appreciate you guys for the help!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.