Johan
Johan

Reputation: 35194

Using evaluated variable values instead of the actual type

var foo;

console.log(typeof foo); //"undefined"

if(typeof foo === 'undefined')
    console.log(1);

if(!foo)
    console.log(2);

In my example above, the console will log both "1" and "2", since undefined evaluates as false. The same thing will happen for null, NaN, "" (empty string) etc.

Is it more common to use the typeof operator and compare the string value, rather than using the evaluated boolean value? Is there any difference besides readability? Any pros and cons?

Upvotes: 0

Views: 51

Answers (1)

zerkms
zerkms

Reputation: 254944

There is no silver bullet and it completely depends on your aims.

If you need to know that variable is "falsy" - you use if (!var), if you need to know precisely if it's null, 0, empty string or whatever - you use if (var === null)

Upvotes: 4

Related Questions