+ 3

Javascript NaN

var a = 10 + null; var b = 10 + undefined; console.log(a+ " " + b); // outputs 10 NaN From what I can see, only the string (represented by " ") is not a number... So why isn't the output 10 NaN 10? What happened to the 10 in var b?

19th Aug 2020, 9:29 PM
Solus
Solus - avatar
2 Answers
+ 9
null is an object that represents a nothing value where undefined is a type. null when used is mathematical operations is treated like the value 0. So for 10 + null is equivalent to 10 + 0, which is equal to the value 10. Where undefined is of a different type than a number. When you try to perform a mathematical operation with undefined it cannot be coerced to a different type or a number type in this case so the result of the operation cannot be evaluated and returns "Not a Number" NaN. https://codeburst.io/understanding-null-undefined-and-nan-b603cb74b44c https://stackoverflow.com/questions/25799408/javascript-null-and-plus-operatior
19th Aug 2020, 9:50 PM
ChaoticDawg
ChaoticDawg - avatar
+ 4
ChaoticDawg The first article does a good job for the most part, but might fall short with some of the explanations. I may post some feedback later to the author to help fill in the gaps later. The two main answers in the 2nd link were fantastic. Thanks for sharing those links. 👌 ---- Solus Building on the explanation by @ChaoticDawg, I'd like to respond to your stated questions: 1. So why isn't the output 10 NaN 10? It might help to see the code rewritten to reflect the evaluated expressions up to the console.log(...) line: var a = 10; //10 + null as a number var b = NaN; // 10 + undefined Now... putting the above together: console.log(10 + " " + NaN); // outputs 10 NaN 2. What happened to the 10 in var b? The var b never received the value 10. b was assigned NaN.
20th Aug 2020, 2:00 AM
David Carroll
David Carroll - avatar