andrewm
andrewm

Reputation: 2642

What is the reasoning behind javascript null zero comparison differences?

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?

Upvotes: 6

Views: 1041

Answers (1)

Felix Kling
Felix Kling

Reputation: 816354

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).

Upvotes: 8

Related Questions