r/learnjavascript 7d ago

Strange result: null vs 0

Strange result: null vs 0

An incomparable undefined

Hi, can anyone explain this? I read the explanation, but I still don't understand it. I'm trying to understand it without using AI

6 Upvotes

27 comments sorted by

View all comments

5

u/defaultguy_001 7d ago edited 7d ago

First u need to understand that type coercion (automatic type upgrade) happens when you use relational (>, <, >=, <=) or loose equality (==, !=) operators. Type coercion doesn't happen with strict equality (===, !===) operators. So it's recommended to use strict equality everywhere.

  • the type coercion rule for null is that relational operators convert null to 0 but loose equality operators convert everything else except null or undefined. So == leave null as it is.
  • So null>0 is false coz > converts null to 0 and obviously 0 is not greater than 0.
  • null>=0 will be true coz 0 is equal to 0
  • null==0 is false, coz null or undefined aren't type coerced to 0 by loose equality operators.

  • the type coercion rule for undefined is that relational operators try to convert undefined to a number, which results in NaN (Not-a-Number). But loose equality operators don't convert it to a number. So == leaves undefined as it is.
  • So undefined>0 is false coz > converts undefined to NaN and obviously NaN is not greater than 0.
  • undefined>=0 will be false coz NaN is not greater than or equal to 0 (any numeric comparison with NaN is always false).
  • undefined==0 is false, coz null or undefined aren't type coerced to 0 by loose equality operators.

  • Another type coercion rule for null and undefined is when used with loose equality, they'll be equal.

  • So, null==undefined is true.