Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reasoning behind javascript null zero comparison differences?

Tags:

javascript

I'm asking this off the back of a Jeff Atwood tweet which shows the following outcomes of null / zero comparison in javascript:

null zero comparison in javascript

I've seen this before and as amusing as it is, I'm wondering if there is actually logic or reasoning behind the behaviour?

like image 730
lisburnite Avatar asked Jun 11 '14 20:06

lisburnite


1 Answers

0 == null is never true. With "loose comparison" null is only equal to itself or to undefined.

However, the relational operator(s) converts its operands to numbers first, if any of those is a number. So, since 0 is a number, null is converted to a number. And the mathematical value to null is 0. So you end up comparing

0 > 0     // nope
0 >= 0    // yes
0 == null // nope, null is only equal to null and undefined
0 <= 0    // yes
0 < 0     // nope

These rules are all defined in the ECMAScript specification (whether they make sense or not is a different question).

like image 52
Felix Kling Avatar answered Oct 09 '22 12:10

Felix Kling