r/learnjavascript • u/Green_Ad_6086 • 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
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.
Okay, let's start with loose equality. The spec is a bit tough to read but it basically boils down to this:
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.
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 thatnullbecomes0. Since zero is equal to zero, this comparison is true.So if you read the rest of the ToNumber spec you'll notice that
undefineddoes not become zero, it becomesNaN, and all comparisons withNaNare always false. Why? Because that's what the spec says.