skip to Main Content

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


  1. 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. (Although return comment works because any non-null object reference is truthy, it’s misleading.)

    Some other methods (for instance, map or sort) expect the callback to return something other than a boolean flag. The map 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 tell sort 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:

    const comment = comments.find(function (comment) {
        return comment.id === 823423;
    });
    

    Or more concisely, by way of parameter destructuring and an arrow function:

    const comment = comments.find(({id}) => id === 823423);
    
    Login or Signup to reply.
  2. The first one is better.

    The second one will be implictly cast to true like the first one. By the way, you should also add return false to both.

    You should try typescript, it can helps you to write better code.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search