var x = null; var y = ... // some number console.info('Comparing null with: ', y); console.info('lt: ', x < y); console.info('gt: ', x > y); console.info('eq: ', x == y); console.info('lte: ', x <= y); console.info('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
For y = 0 we get:
Comparing null with: 0 lt: false gt: false eq: false lte: true gte: true
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
null is greater than a negative number! 🙂
The conclusion is that you must be very cautious with
null then all these comparing expressions should use parseInt(x) instead of x. The value of
NaN (not-a-number) which behaves nice (in line with common reason) when compared to numbers. So now we have:
console.info('Comparing null with: ', y); console.info('lt: ', parseInt(x) < y); console.info('gt: ', parseInt(x) > y); console.info('eq: ', parseInt(x) == y); console.info('lte: ', parseInt(x) <= y); console.info('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