2

I'm currently transitioning from promises to async await. And its been easier to reason about code. I just have a question on if using way to check for undefined is good. The code is being used in nodejs and checking against a database. The code goes something like this.

Edit: I am aware that I'm supposed to catch for errors. I just got lazy here.

// This is a hypothetical function
async function retrieveUser(userID){
  let user = await databasefetchfuction(userID);
  if(user) return user;
  return;
}

controller.getUser = async function(req,res){
 let user = await retrieveUser(req.params.userID);
 if(!user){ // Is this ok?
   return res.status(404).json();
 } 
 return res.status(200).json({ user });
}

I was if doing this is fine or if I should explicitly check for undefined using user === undefined?

  • 2
    I'm voting to close this question as off-topic because it is asking for [a code review](https://codereview.stackexchange.com/help/on-topic) – Quentin Apr 19 '17 at 13:00
  • Depends really. Are any of `false`, `""`, `0`... valid return values or should they be errors too? – Niet the Dark Absol Apr 19 '17 at 13:00
  • 1
    Your current form will return properly for the following values: `null`, `undefined`, `NaN`, `empty string ("")`, `0`, `false` – Tyler Roper Apr 19 '17 at 13:01
  • Isn't the real question will this check if my method returned a value? What do these methods do exactly? The result will depend on that. – Liam Apr 19 '17 at 13:03
  • @Quentin I'm not really asking for a code review. The purpose of the code was to show an example. This code is fictitious. I just want to confirm behaviour. –  Apr 19 '17 at 13:03

3 Answers3

2

if(!user) is fine as long as you are willing to accept that it will be true for all the other "falsey" things in JS.

See this: All falsey values in JavaScript

Community
  • 1
  • 1
gforce301
  • 2,944
  • 1
  • 19
  • 24
0

Using !var is perfectly fine in the case of a database return. There is no way that a user was found but !var returns true.

itsundefined
  • 1,409
  • 2
  • 12
  • 32
0

The undefined value in JavaScript is treated as a falsy value, so yes - you are doing it in a proper way. If you want to check other field in user object, you should check both user and user.property.

TheOpti
  • 1,641
  • 3
  • 21
  • 38