Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does NaN != undefined?

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...

like image 505
oodavid Avatar asked Apr 19 '13 13:04

oodavid


People also ask

Is NaN equal undefined?

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.

What does NaN undefined mean?

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.

What is the difference between NaN and undefined?

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.

Why null == undefined is true?

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.


2 Answers

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.

like image 72
Naftali Avatar answered Sep 17 '22 22:09

Naftali


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.

like image 34
Ja͢ck Avatar answered Sep 20 '22 22:09

Ja͢ck