0

According to this MDN link, the find() method takes a callback function that can take three arguments: the current array element, the index of the current array element, and the array that the method is being called upon.

So:

var r = [2, 9, 11]; console.log(r.find(function(e, i, r) {
    if (e % 2 === 0)
        return e; }))

returns 2, as I would expect.

However:

var r = [2, 9, 11];
console.log(r.find(function(e, i, r) {
    if (e % 2 === 0)
        return i;
}))

return undefined (when I expect 0),

and

var r = [2, 9, 11];
console.log(r.find(function(e, i, r) {
    if (e % 2 === 0)
        return r;
}))

returns 2 (when I expect [2, 9, 11]).

Can someone please explain what I am not properly understanding?

2 Answers 2

5

The callback you pass to .find() is assumed to return a boolean (true or false) value. The value returned from .find() is the value of the first element for which the callback returned a non-false value.

In your first example:

var r = [2, 9, 11]; console.log(r.find(function(e, i, r) {
    if (e % 2 === 0)
        return e; }))

the return value is 2 not because of return e; returning the value 2, but because 2 is truthy. You can verify that by changing return e to return true or any other truthy value.

Similarly, in the second example:

var r = [2, 9, 11];
console.log(r.find(function(e, i, r) {
    if (e % 2 === 0)
        return i;
}))

your callback returns 0 on the first element (because i is 0), but that's not truthy.

Sign up to request clarification or add additional context in comments.

Comments

2

The find method executes the callback function once for each element present in the array until it finds one where callback returns a true value.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

The callback return is only used to indicate if the current value should be the result or not. It's sort of like find asking your callback a "yes or no" question for the current value.

In your second case, 2 passes e % 2 === 0 and you returned i. However i is 0, a falsy value so find skips over that and continues. Further values (9 and 11) don't pass e % 2 === 0. Functions that don't explicitly return a value return an undefined, a falsy value. In the end, no callback returned a truthy value and findreturns undefined.

The third case, 2 passes e % 2 === 0 and you returned r, an array, which is a truthy value. That made find, right off the bat, return the first item which is 2.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.