JavaScript Comparison operation at a glance

1 minute read

When given a scenario like:

1console.log(null > -1) //true

It produces true, which makes me think null is treated as 0. But when I run:

1console.log(null == 0) // false
2console.log(null > 0) // false
3console.log(null < 0) // false

They all output false!

I googled a lot and finally found answers in Ecma-262 Specification.

The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:

 11. If Type(x) is the same as Type(y), then return the result of performing Strict Equality Comparison x === y.
 22. If x is null and y is undefined, return true.
 33. If x is undefined and y is null, return true.
 44. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
 55. If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
 66. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
 77. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
 88. If Type(x) is either String, Number, or Symbol and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).
 99. If Type(x) is Object and Type(y) is either String, Number, or Symbol, return the result of the comparison ToPrimitive(x) == y.
1010. Return false.

Relational comparison is much more complex so I’m not copying that section. Read at the spec website.

TL;DR

Anyway it seems that in null == 0, null is treated just as is, and equality comparison between null and Number always return false (No 10). But when it comes null > -1, null is conversed to 0 using ToNumber() algorithm.

Read more:

comments powered by Disqus