First of all, my apologies for any mistakes in my question as I have very less idea about asking questions.
I came up with these two cases :-
const comment = comments.find(function (comment) {
if (comment.id === 823423) {
return true;
}
});
And this:-
const comment = comments.find(function (comment) {
if (comment.id === 823423) {
return comment;
}
});
What’s the difference between the two as I tried to run both the code and it gave the same result and which one is a better practice?
2
Answers
The
find
callback is expected to return a boolean flag (a truthy or falsy value), where a truthy value means the item is what you’re looking for. So semantically,return true
is correct. (Althoughreturn comment
works because any non-null
object reference is truthy, it’s misleading.)Some other methods (for instance,
map
orsort
) expect the callback to return something other than a boolean flag. Themap
method expects you to return the item that should be in the resulting mapped array;sort
expects a number (where negative, zero, and positive values tellsort
the relative ordering of the elements the callback is passed for comparison). Whenever you’re not sure what the callback should return, check the MDN documentation (or any good reference).In your specific example, you’re relying on implicitly returning
undefined
when the ID doesn’t match (because in that case, the callback never explicitly returns a value). Instead, you should explicitly return a falsy value. The simplest way is to just directly return the result of the comparison:Or more concisely, by way of parameter destructuring and an arrow function:
The first one is better.
The second one will be implictly cast to
true
like the first one. By the way, you should also addreturn false
to both.You should try typescript, it can helps you to write better code.