Why NaN! = Undefined?

According to the Mozilla Docs :

An undefined value is converted to NaN when used in a numeric context.

So why are both values ​​equal to true ?:

NaN != undefined NaN !== undefined 

I could understand Nan !== undefined , since the type of the variable would be different ...

+6
source share
2 answers

NaN by definition of " Not Number "

This does not mean that it is undefined - it is explicitly defined , but undefined in a sense that it is not a number.

+12
source

This is because, according to Section 4.3.23 of the ECMAScript Language Specification, NaN is defined as:

a numeric value that is an IEEE 754 "Not-a-Number" value

So this is a number, not something undefined or null. The meaning is further explained in Section 8.3.

...; to the ECMAScript code, all NaN values ​​are indistinguishable from each other.

A comparison of equality with NaN is defined in Section 11.9.3 :

A comparison of 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 comparison, you should use isNaN() instead:

 isNaN(NaN) // true 

Update

The value +undefined not a number, but it is nonetheless (albeit with a special value) and therefore not undefined. Just like casting undefined for a string gives a string value that is defined.

+2
source

All Articles