-1

I understand the implicit coercion that happens in javascript, but i actually can't understand why this happens:

isNaN(1 + null)      // false
isNaN(1 + undefined) // true

As i know that JS convert the null & undefined to 0, Or we could say consider them false value.

what is the difference here ?

Mahmoud Fawzy
  • 1,635
  • 11
  • 22

1 Answers1

3

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

Community
  • 1
  • 1
Mahmoud Fawzy
  • 1,635
  • 11
  • 22
  • Why are you asking if you already have the answer? – connexo Oct 12 '19 at 10:26
  • 3
    It‘s certainly right that values are coerced differently depending on context. If you do `if(x)` then the value of `x` is converted to a boolean. `a + b` with either being a number expects the other one to be a number. Similarly if one is a string the other will be converted to a string. – Felix Kling Oct 12 '19 at 10:27
  • 1
    @connexo Probably to share the knowledge with the world. [Self-answers are fine and actually encouraged](https://stackoverflow.com/help/self-answer). – Ivar Oct 12 '19 at 10:28
  • it's okay to answer your own question in stack @connexo – Mahmoud Fawzy Oct 12 '19 at 10:30