I'm reading in my book, "Elegant JavaScript", that null == true
evaluates as false. Using an interpreter, I have confirmed this to be TRUE
. However, later in the chapter--in fact, on the same page--, it says that when null is given as the condition of an if, while, or for statement, it will be converted to a Boolean and return false.
Can anybody with a deeper insight tell me why this is? I know where to find browser source code, but I'm not sure how to target the programming that is responsible for this peculiar and unintuive behavior. Because I know very little C++, I would also appreciate any tips on finding info like this, independently.
Thank you.
An important distinction to make is that the Type
of null
is Null
.
(ignore typeof
it returns "object"
for null
because of bad design and backwards compatibility)
11.9.3 The Abstract Equality Comparison Algorithm # Ⓣ The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:
[... stripped]
- Return false.
The ES5 specification
Says that the comparison with null
and a Boolean
should return false because the Type
of Null
and Boolean
are not the same, and none of the other steps in 11.9.3 apply so the default action of return false
happens
The only case where the Type
of x
and y
are different and either x
or y
is null
but the ==
operation still returns true
are
If x is null and y is undefined, return true.
If x is undefined and y is null, return true.
That means undefined == null
returns true
Of special note:
There is an ES6:harmony proposal to fix typeof null
Actually I think he refers to the fact that typeof null == 'object'
, which is unfortunately the case. But that's a peculiarity of the typeof operator, not of null itself. Null is falsy value, but typeof returns "object" for it, according to the spec: http://bclary.com/2004/11/07/#a-11.4.3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With