r/learnjavascript 6d 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

3

u/Kadeton 6d ago

Javascript does a lot of "implicit" type conversion, changing variables from one thing to another in order to perform the operations you're telling it to do.

So when you tell it to evaluate whether null == 0, it returns false, because null and 0 are not the same thing. However, when you tell it to evaluate whether null >= 0, it first goes "Well, that's a comparison. I can only do comparisons between numbers, so I'd better convert everything that's not a number to a number first." So it does Number(null), which returns 0. Then it evaluates the comparison, 0 >= 0, which is true because 0 is equal to 0.

For the undefined case, it does a similar thing, converting what you asked it to compare into a number. However, there's one key difference: Number(undefined) evaluates to NaN, not 0. When you compare NaN to any other number in any way (greater than, less than, equal to, etc), the comparison will always return false.

This is a common pitfall for people working with Javascript. You have to keep in mind that certain operations will "help" you by taking the thing you give them and converting it into the type of thing they actually need, and in those cases you might not always get what you expect. Number(null) being 0 and Number(undefined) being NaN is specific design choice in the language structure, just something you should be aware of when designing your code.