On Aug 4, 12:08 am, Metre Meter wrote:
> Hi there,
>
> I came across an aspect of Javascript I hadn't considered
> before.
>
> Null compares equal (==) to another null, or to undefined
> and not to anything else. Logically, therefore it shouldn't
> compare equal to a boolean false value- and as expected
> this code:-
>
> if (null == false) {
> alert('Yes');
> } else {
> alert('No');
> }
>
> displays "No".
>
> Yet, if the condition above is changed to simply "if (null)
> {...} else {...}", the result shown is "No", implying that
> null on its own *is* considered "false". Yet it isn't
> considered "equal" to the boolean false.
>
> So can I assume that null is considered false in a boolean
> context,
Insofar as there is a "boolean context" that would be context where
the internal ToBoolean function is applied to the result of evaluating
an expression. The ToBoolean function returns false for null,
undefined, zero, NaN, the empty string and boolean false.
> yet doesn't match (i.e. return a true value for) a comparison
> with a boolean value? While logical, this seems strange.
Taken in isolation, maybe, but undefined behaves the same as null, and
NaN type-converts to false, but is not equal to any value, including
itself.
> Can someone confirm (or otherwise) this
The results of your observations correspond with the correct
behaviour.
> and/or explain the situation
> in more depth? Thank you!
The depth comes from understanding the applicable algorithms from ECMA
262. Why the algorithms are as they are is no something that cannot be
given a definitive answer by anyone but the authors of the
specification (and possibly not even them).
Richard.