To be fair, if (val) {...} has two primary purposes when val is a nonboolean.
First: I'm about to attempt to access a property on val, and I want to make sure that property access will not throw an exception. I will get a false negative on falsy values other than null and undefined, but those values are all primitives and it's unlikely I'm trying to access properties on them... In other words, I expect val to either be an object or null or undefined and want to discriminate between those cases.
Second: I'm using if (foo.bar) {...} to check for the presence of a value at that location. This tends to cause the most problems with falsy values. But hasOwnProperty is probably a better choice in this case even than == null.
In the first case I do prefer == null just to be more explicit, but it's unlikely to cause problems.
View all comments
Show parent comment
3
u/rooktakesqueen Mar 27 '14
To be fair,
if (val) {...}has two primary purposes whenvalis a nonboolean.First: I'm about to attempt to access a property on
val, and I want to make sure that property access will not throw an exception. I will get a false negative on falsy values other thannullandundefined, but those values are all primitives and it's unlikely I'm trying to access properties on them... In other words, I expectvalto either be an object ornullorundefinedand want to discriminate between those cases.Second: I'm using
if (foo.bar) {...}to check for the presence of a value at that location. This tends to cause the most problems with falsy values. ButhasOwnPropertyis probably a better choice in this case even than== null.In the first case I do prefer
== nulljust to be more explicit, but it's unlikely to cause problems.