why (null <= 0) is true?

Brendan Eich brendan at mozilla.com
Mon Sep 24 23:21:13 PDT 2012


Frank Quan wrote:
> null == 0 // false
> null > 0 // false
> null < 0 // false
>
> null >= 0 // true
> null <= 0 // true
>
> The above expressions are weird compared to the all-false "undefined". 
> Why doesn't the spec treat null like undefined?

This is not really a question whose answer can change (not by default, 
anyway). Perhaps some day with opt-in metaprogramming of operators 
within a lexical scope.

The spec was not made up first, then implemented. The first 
implementation, by me in Netscape 2 in 1995 done in 10 days, included 
user-testing on some developers who really wanted something broken for 
==, and I foolishly gave it to them (and to everyone).

The difference you see above is not specifically due to null vs. 
undefined, rather to == vs. the relational operators. Relationals 
convert to Number (the spec's term for the IEEE double type reported by 
typeof as "number"), and null converts to 0:

js> +null
0

The broken Equality operators == and != are more complicated, but in 
this case they at least do not convert null at all, rather they notice 
that its type is Null (ECMA spec term) and not the same as the 
right-hand side, which is Number, and so (based on both types not being 
caught by earlier steps in 11.9.3) the result for == is always false, != 
always true.

The non-conversion of null in this case is actually good. Doesn't make 
up for all the broken-ness, though.

/be


More information about the es-discuss mailing list