tags:

views:

84

answers:

3

What is the 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?

A: 

see this and the comment of Jerod Venema

NULL is neither true nor false, it's a non state

Andreas Niedermair
+2  A: 

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.

Andrzej Doyle
As in Object Oriented Js Book, All values become true when converted to boolean, with the exception of the six falsy values: 1. ""2. null3. undefined4. 05. NaN6. false
Lakshman
If we're talking about specifications, check out http://interglacial.com/javascript_spec/a-11.html#a-11.9.3 (not the definitive ECMA copy, but that's a PDF so not hot-linkable). The rules for the equals operator show why your example returns false (it falls through to point 22). This doesn't change my general advice though, to use `===` instead in almost all situations.
Andrzej Doyle
+1, good explanation. @Lakshman, the point is, `if(foo)` converts foo to boolean, but `bool==foo` doesn't.
stereofrog
A: 

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: http://stackoverflow.com/questions/1995113/strangest-language-feature has a javascript truth comparison table.

Graza