0

I want to ask about a weird javascript thing. All of these conditions, in my opinion, contradict each other and return false:

  • 0 > null
  • 0 < null
  • 0 == null
  • 0 === null

Why does using >= and <= operators return true? >= means gt and <= means lt. They couldn’t be equals. Moreover, “null” has a null value, 0 has a null value and, for the logic 0 > null should return true. Could someone explain me this fact?

Nissa
  • 4,636
  • 8
  • 29
  • 37
Mattew
  • 3
  • 2
  • All these values are false. And rightly so. Because they ARE quite obviously false. Simply because 0 and null are treated as false in an if construct does not mean that these values are equivalent. – ManoDestra May 27 '16 at 20:01
  • 1
    Welcome to StackOverflow, @mattew. JavaScript operators are a very common source of puzzlement to people new to the language and most of their oddness revolves around the concept of `type coercion`. I've linked you to one question here that covers that question some. If you google for the phrase `javascript type coercion` you will come across page after page of explanations. – Jeremy J Starcher May 27 '16 at 20:02
  • jeremy and rexell, my question is different. – Mattew May 27 '16 at 20:03
  • >= and <= don't mean gt and lt. They are the best JavaScript equivalents (because it was designed for ASCII-only) for ≥ and ≤, respectively. – Nissa May 27 '16 at 20:03
  • The answer provided by @raxell answers your question exactly, as far as I can see. – Sam May 27 '16 at 20:06
  • @Mattew `null` is coerced to Number. `Number(null)` is zero, so 0 >= 0 is obviously true, while 0 > 0 is false. – raxell May 27 '16 at 20:08

1 Answers1

1

When you use > and <, null is converted to the number 0. 0 > 0 and 0 < 0 are both false (that's basic math). When you use == and ===, null is not converted. 0 is not equal to null and hence both are false as well.

More generally speaking: Operators are defined for specific data types and if you pass a value of a different data type that value will be converted to the expected data type first. > and < are defined for strings and numbers but not for null. Hence null is (eventually) converted to a number.

== are a little different ===. While == usually performs type conversion, it doesn't do that if you compare against null. That's simply how the algorithm works.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143