Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript equality returns false [duplicate]

Possible Duplicate:
Why `null >= 0 && null <= 0` but not `null == 0`?

All suppose to be true:

alert( "null==undefined:  " + (null == undefined) )
alert( "null==0:          " + (null == 0) )       // why false??
alert( "false=='':        " + (false == '') )
alert( "true==1:          " + (true == 1) )
alert( "true=='1':        " + (true == '1') )
alert( "'1'==1:           " + ('1' == 1) )

All suppose to be false:

alert( "null===undefined:  " + (null === undefined) )
alert( "null===0:          " + (null === 0) )  
alert( "false==='':        " + (false === '') )
alert( "true===1:          " + (true === 1) )
alert( "true==='1':        " + (true === '1') )
alert( "'1'===1:           " + ('1' === 1) )

Why (null == 0) is false

I use last chrome to test it.

like image 599
ses Avatar asked Jan 31 '26 11:01

ses


1 Answers

The null type is not really comparable with the number type, so the comparison algorithm returns false. From the spec (omitted the associative cases):

  1. If the types are equal, use a type-specific comparison.
  2. null == undefined is true
  3. numbers and strings are compared as numbers, the string is converted
  4. If a boolean is compared, it is converted to a number and compared again
  5. If numbers or strings are compared with objects, the object is converted to a primitive and compared again - and no, Type(null) is Null, not an object (as in the typeof operator).
  6. For everything else, return false.
like image 72
Bergi Avatar answered Feb 02 '26 02:02

Bergi