M
Metre Meter
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,
yet doesn't match (i.e. return a true value for) a comparison with a
boolean value? While logical, this seems strange.
Can someone confirm (or otherwise) this and/or explain the situation
in more depth? Thank you!
- MM
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,
yet doesn't match (i.e. return a true value for) a comparison with a
boolean value? While logical, this seems strange.
Can someone confirm (or otherwise) this and/or explain the situation
in more depth? Thank you!
- MM