5
Nov 09
0

Less than Null

Here’s a fun javascript tidbit that can bite you if you aren’t careful:

>>> null >= 0
=> true
>>> null <= 0
=> true
>>> null > 0
=> false
>>> null < 0
=> false
>>> null == 0
=> false

I can’t think of any way to make this more inconsistent. In C# the expression will always evaluate to false (and you get a compiler warning, but let’s not get into that). In ruby, a NoMethodError is raised because the < operator is treated as a method on the nil object.

Unfortunately, due to the weakly-typed nature of javascript you are more likely to run into this problem than you might think. Because

>>> "0" == 0
=> true

there is a good chance you will find yourself comparing strings to integers, and eventually, null to integers.

No idea where the designer of javascript came up with this functionality, but now that I found it, I’ll be watching out for any potential null comparisons in the future.

Leave a comment

(required)

(not published) (required)