31

How should I understand these?

null>0
> false

null==0
> false

null>=0
> true
eonil
  • 83,476
  • 81
  • 317
  • 516
  • Web Inspector console of Safari 5 (most recent version) – eonil Jul 30 '10 at 14:33
  • Similar to http://stackoverflow.com/questions/2910495/why-null-0-null-0-but-not-null-0 - has some more interesting answers though CMS's answers in both are the best reference. – bschandramohan Jun 11 '14 at 04:48

4 Answers4

23

The relational operators (>= and <=), perform type coercion (ToPrimitive), with a hint type of Number, all the relational operators present have this behavior.

You can see the inner details of this process in the The Abstract Relational Comparison Algorithm.

On the other hand, the Equals operator (==), if an operand is null it only returns true if the other is either null or undefined, no numeric type coercion is made.

null == undefined; // true
null == null; // true

Check the inner details of this process in the The Abstract Relational Comparison Algorithm.

Recommended articles:

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
6

The relative comparison operators imply a numeric context, so in those cases (>, >=) the null is converted to a number (zero).

In the == case, however, both values are treated as boolean values, and Javascript doesn't think that null should be equal to any other "falsy" values. It's kind-of weird. The equality algorithm for == has a bunch of special cases, and null is one of those. It's only == to itself and undefined.

Pointy
  • 405,095
  • 59
  • 585
  • 614
2

When null is used in a numeric experession it evalutes to 0, that explains your > and >= cases.

== is more subtle. Informally, null is not the same as zero, so it kind of makes sense.

djna
  • 54,992
  • 14
  • 74
  • 117
  • [This](http://bclary.com/2004/11/07/#a-11.8) is a very very useful link to understanding the steps taken in using these operators. Still doesn't explain the crazy logic, but meh... – Stephen Jul 30 '10 at 14:29
0

Interesting! It seems like Javascript needs a couple new identity operators like >== and <==. Although I am not sure that would make much sense, given the numerical implications of > and <.

This gives the expected result...

(null > 0 || null === 0);
Josh Stodola
  • 81,538
  • 47
  • 180
  • 227