JavaScript, comparing numbers and null

Last time I’m programming quite a lot in JavaScript. And I discovered this kind of inconsistency when comparing a null value with numbers. Let’s consider this code in JavaScript:

var x = null;
var y = ... // some number'Comparing null with: ', y);'lt: ', x < y);'gt: ', x > y);'eq: ', x == y);'lte: ', x <= y);'gte: ', x >= y);

I was assuming null value compared to numbers will behave in a way somehow similar to that like NULL is behaving in SQL. Or at least I was assuming all above comparing expressions will be evaluated to false. The reality is even worse! Results are depending on a number which is value of y variable.

For y = 3 we get:

Comparing null with: 3
lt: true
gt: false
eq: false
lte: true
gte: false

So it looks null is considered in JavaScript to be less than 3.

For y = 0 we get:

Comparing null with: 0
lt: false
gt: false
eq: false
lte: true
gte: true

Total nonsense! null is not less than 0 and is not equal to 0 but… it’s less or equal to 0.

For y = -3 we get:

Comparing null with: -3
lt: false
gt: true
eq: false
lte: false
gte: true

At least we know JavaScript “thinks” null is greater than a negative number! 🙂

The conclusion is that you must be very cautious with null value in JavaScript. It should not be compared with numbers as results are against the logic.

Disclaimer: I was executing JavaScript in console of Firefox ver. 50.

BTW: It looks there are more inconsistencies in JavaScript! 😀


If you need to compare a variable against numbers in JavaScript and it’s possible this variable can be null then all these comparing expressions should use parseInt(x) instead of x. The value of parseInt(null) is NaN (not-a-number) which behaves nice (in line with common reason) when compared to numbers. So now we have:'Comparing null with: ', y);'lt: ', parseInt(x) < y);'gt: ', parseInt(x) > y);'eq: ', parseInt(x) == y);'lte: ', parseInt(x) <= y);'gte: ', parseInt(x) >= y);

Now all these expressions will evaluate to false no matter what number is the value of variable y.

NOTE: If your variable (like x in the example above) is going to hold floating-point numbers then use parseFloat instead of parseInt.

About krzysztoftomaszewski

I've got M.Sc. in software engineering. I graduated in 2005 at Institute of Computer Science, Warsaw University of Technology, Faculty of Electronics and Information Technology. I'm working on computer software design and engineering continuously since 2004.
This entry was posted in JavaScript. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s