I am wondering why undefined == undefined
but NaN != NaN
.
Javascript null represents the intentional absence of any object value. The undefined property indicates that the variable has not been assigned a value or not declared at all. The NaN property represents a “Not-a-Number” value. The NaN property indicates that a value is not a legitimate number.
When NaN is one of the operands of any relational comparison ( > , < , >= , <= ), the result is always false . NaN compares unequal (via == , != , === , and !== ) to any other value — including to another NaN value.
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.
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.
Because that's how it is defined in both the Abstract Equality Comparison Algorithm, and the Strict Equality Comparison Algorithm.
If either operand to ==
or ===
is NaN
, it returns false
.
Abstract
- If Type(x) is Number, then
- If x is NaN, return false.
- If y is NaN, return false.
- If x is the same Number value as y, return true.
- If x is +0 and y is −0, return true.
- If x is −0 and y is +0, return true.
- Return false.
EDIT: The motivation for the unequal comparison as noted by @CMS is compliance with the IEEE 754 standard.
From the Wikipedia link provided in the comment below:
...The normal comparison operations however treat NaNs as unordered and compare −0 and +0 as equal. The totalOrder predicate will order these cases, and it also distinguishes between different representations of NaNs and between the same decimal floating point number encoded in different ways.
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