Search code examples
javascriptc++typesprogramming-languagestype-conversion

Null is type object, so it's truthy? What's going on behind the scenes?


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.


Solution

  • 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]

    1. 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