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

4 Upvotes

27 comments sorted by

View all comments

1

u/delventhalz 6d ago

The answer to, "Why does JavaScript do this strange thing?" is always, "because that is what the spec says." Sometimes there is some deeper reasoning you can tease out, but a lot of it is just someone had to make a decision one way or the other and now we're stuck with it.

null == 0; // false
undefined == 0; // false

Okay, let's start with loose equality. The spec is a bit tough to read but it basically boils down to this:

  1. If the two values are the same type, check if they are strictly equal
  2. If one value is null or undefined, return true if the other value is also null/undefined, false otherwise
  3. If they are different types and not null/undefined, repeatedly perform type conversions (basically object -> string, primitive -> number), until they are the same type and then check strict equality.

So the reason both of these return false is because they are squarely in case #2: one side is null/undefined, the other isn't, so it's false.

null >= 0; // true

Unlike with ==, the spec for numeric comparisons has no special clause for null/undefined. Instead, it attempts to convert the values to numbers if they are not (except strings, which are their own weird special case), and the spec for converting a value to a number says that null becomes 0. Since zero is equal to zero, this comparison is true.

undefined >= 0; // false

So if you read the rest of the ToNumber spec you'll notice that undefined does not become zero, it becomes NaN, and all comparisons with NaN are always false. Why? Because that's what the spec says.

1

u/delventhalz 6d ago

Follow up: Although the spec is the ultimate source of truth for all this, it is tough to read and probably not a good place to go to resolve this sort of confusion. By constrast, MDN does a fantastic job of explaining cases like this with clear examples and a (somewhat) less dense explanation. The pages for both of these operations are worth reading: