0

I don't understand the difference between these two ways of checking if a variable is undefined:

if (typeof res.locals.user.hashnodes === 'undefined') {
        morphemes = 0;
}

and

if (!res.locals.user.hashnodes) {
       morphemes = 0;
}

For me, only the second option works, the first one doesn't. Anyone knows why?

(res.locals.user are the user settings I pass in my Node Js app).

Thank you!

4
  • Most likely because res.locals.user.hashnodes is not undefined, but a different kind of falsy value (e. g. null, false or 0). Commented May 25, 2014 at 14:14
  • would ! work on an undefined one? or I need to make two checks then if I want to cover all the possibilities? Commented May 25, 2014 at 14:15
  • Are you getting a JavaScript error and if so what is it? Or is the logic not functioning as you expect? Commented May 25, 2014 at 14:15
  • @deemeetree Yes, it would, since undefined is a falsy value. Commented May 25, 2014 at 14:22

3 Answers 3

1

if (!res.locals.user.hashnodes) will also check for existing yet false values. 0, false, '', null, 'undefined', [] will all evaluate to true if you only use !.

(Here's a more thorough list of what evaluates to what)

So what value does your local hold?

console.log(typeof res.locals.user.hashnodes)

If it's anything else than 'undefined', there's your answer

Sign up to request clarification or add additional context in comments.

Comments

1

JavaScript has the so-called falsey variables, this means that !res.locals.user.hashnodes evaluates to undefined, 0, false and a few more. Here's some more info on falsey and truthy variables.

http://www.sitepoint.com/javascript-truthy-falsy/

Comments

1

The second will set morphemes = 0 if res.locals.user.hashnodes is undefined or false or null or 0

where as the fist will only do so it it is undefined

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.