According to the Mozilla docs:
The undefined value converts to NaN when used in numeric context.
So why do both of the following equate to true?:
NaN != undefined
NaN !== undefined
I could understand Nan !== undefined
as the variable type would be different...
NaN values are generated when arithmetic operations result in undefined or unrepresentable values. Such values do not necessarily represent overflow conditions. A NaN also results from attempted coercion to numeric values of non-numeric values for which no primitive numeric value is available.
NaN (Not a Number) is a numeric data type that means an undefined value or value that cannot be represented, especially results of floating-point calculations.
undefined isn't converted into any number, so using it in maths calculations returns NaN. NaN (Not-A-Number ) represents something which is not a number, even though it's actually a number.
undefined is a primitive type of a variable which evaluates falsy, has a typeof() of undefined, and represents a variable that is declared but missing an initial value. null == undefined evaluates as true because they are loosely equal.
NaN is by definition "Not a Number"
That does not mean it is undefined -- it is clearly defined -- but undefined in a sense that it is not a number.
This is because, according to Section 4.3.23 of ECMAScript Language Specification NaN
is defined as:
number value that is a IEEE 754 “Not-a-Number” value
So it's a number and not something undefined or null. The value is explained further in Section 8.3
...; to ECMAScript code, all NaN values are indistinguishable from each other.
Equality comparisons with NaN
are defined in Section 11.9.3:
The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows: If Type(x) is Number, then:
If x is NaN, return false.
If y is NaN, return false.
For the purpose of comparison you should use isNaN()
instead:
isNaN(NaN)
// true
Update
The value of +undefined
is not-a-number, but it's a number nonetheless (albeit with a special value) and therefore not undefined. Just like how casting undefined
to a string yields a string value that's defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With