Javascript converts null
to 0 but undefined
is converted to NaN
.
check it out using the built in fucntion Number
.
So in this case (1+ null)
is similar to 1+ 0
which is 1
and (1+ undefined)
is similar 1 + NaN
which is NaN
.
That's why it returns true.
console.log(Number(null));
console.log(Number(undefined));
The weird behavior here though is that Javascript consider both of these types "false" when dealing with comparison operator or as a condition in if statement and false value considered 0 after implicitly coerced...
Conclusion: Js coerce undefined & null
depending on the situation. if it's in condition, it try to convert it to boolean false
& if it's in an arithmetic operation it try to convert it to numbers, in this case there would be difference between them:
undefined ==> NaN
null ==> 0