Javascript - value of document.write(false == null)
What is the 开发者_Python百科value of document.write(false == null)
. It should be true right (converted to same type before comparing - null is converted to false), if null is false then comparision should return true, but printing false. Why?
Your initial assumption is incorrect (as you may have worked out by the output!). ==
does indeed do type coercion, but there result is not necessarily what you expect. null
is an object, whose type is null - false
is an object whose type is boolean. There is no coercion under which objects of the null
and boolean
types can be equal, which is why this is false.
undefined
objects, on the other hand, can be coerced to null.
Note that the double-equals operator behaves in a bizarre way due to this - it's not even transitive. I would strongly suggest against its use unless somehow you know exactly how it will behave under your domain of inputs and you're sure you want this. It will almost certainly be better to coerce manually and use the ===
operator instead.
Edit: my original answer was completely incorrect....the below IS correct
(false == null) === false
(!null) === true
The 4th or 5th most popular answer in this post: Strangest language feature has a javascript truth comparison table.
精彩评论