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?
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’snull,0, empty string or whatever – you useif (var === null)