Why 'null' in function?

Tell us what’s happening:

Hi, before i start, i apologize for my english skills…
I got just one question, why we put null arguments ?
Like this for exemple :

var findPeopleByName = function(personName, done) {
  Person.find({name: personName}, function (err, personFound) {
    if (err) return console.log(err);
    done(null, personFound);
  });

If someone can help me, that will be very kind ! :smile:
Thank you,
Have a great day !
Your code so far

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0.

Challenge: Use model.find() to Search Your Database

Link to the challenge:

Hello!

First of all, welcome to the forum! We hope you learn a lot :partying_face:!

I’ll start by saying that the callback function to Person.find is not right; it will create problems in the future because the done function is not called when there is an error:

if (err) return console.log(err); // This line is wrong

One correct way of doing it is this:

if (err) {
  console.error('Could not find the person ' + personName);
  return done(err); // The function actually exists the Promise.
}

Now, back to the main issue, we’re using null because the done function expects two parameters:

  1. The first one is the error and
  2. The second one is the successful object to be returned.

If we passed anything other than null to the done function it’s assumed that there was an error, even if the actual person was found.

For instance, if I used your findPeopleByName function, I would write something like this:

findPeopleByName('a person', function(error, thePerson) {
  if (err) {
    // Log the error so the developer can see the problem
    console.error('Something went wrong when trying to find a person by name:', error);
    return; // In this example, we don't do anything else
  }
  console.log('We found the user: ', theUser); // Here's where the program would end
});

If you always passed anything, other than null or undefined, then the first if would always be true. Of course, it will always depend on how the caller uses the callback (in this case, the done function).

Does this help?

2 Likes