Null is type object, so it's truthy? What's going on behind the scenes?-Collection of common programming errors
When you compare null
to true
, it’s evaluated as so it’s not equal to false
,true
. Similarly, when used in any other context where it must be treated as a boolean — like an if
or while
expression — it’s false
.
It’s not really correct to say that “null is type object”, because it is not. It is null
. It doesn’t really have any type, (Thanks @Roee Gavirel) It’s got it’s own type (the null type) because it isn’t anything. In other words, if a variable has the value null
, that means that it is referring to nothing; no object at all.
edit — crap hold on a sec because my brain’s still asleep.
OK here’s what’s in the spec. If one of the operands of ==
is boolean, then the boolean is converted to a number (yes really) and the conversion proceeds that way. That’s why null
is ==
to neither true
nor false
. The “strangeness”, therefore, is not so much about null
as it is about the complicated rules for evaluating ==
comparisons.
Section 11.9.3 of the ECMA-262 standard spells it all out in a more-or-less understandable way. Suffice to say that the semantics of ==
are not at all simple.
Originally posted 2013-11-09 23:06:05.