user6127082
user6127082

Reputation:

Is this a good way to check for undefined values in javascript?

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?

Upvotes: 2

Views: 3292

Answers (3)

gforce301
gforce301

Reputation: 2984

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

Upvotes: 2

TheOpti
TheOpti

Reputation: 1661

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.

Upvotes: 0

itsundefined
itsundefined

Reputation: 1450

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.

Upvotes: 0

Related Questions