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!

Aerodynamika
  • 7,883
  • 16
  • 78
  • 137

3 Answers3

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/

Jon Snow
  • 3,682
  • 4
  • 30
  • 51
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

andrew
  • 9,313
  • 7
  • 30
  • 61
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

casraf
  • 21,085
  • 9
  • 56
  • 91