oodavid
oodavid

Reputation: 2326

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

Upvotes: 8

Views: 17315

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173532

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.

Upvotes: 2

Naftali
Naftali

Reputation: 146302

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.

Upvotes: 14

Related Questions