SoFunction
Updated on 2025-02-28

JavaScript NaN and Infinity Special Values ​​[Translation]



In JavaScript, NaN represents "not a number". This value will be returned mainly when an error occurs in parsing a string:
Copy the codeThe code is as follows:

> Number("xyz")
NaNNaN


The name is "not a number", but it can also be said to be not a number:
Copy the codeThe code is as follows:

> NaN !== NaN
true

It is a number! Type is "number"
Copy the codeThe code is as follows:

> typeof NaN
'number'

1.1 Detection of NaN
In JavaScript, NaN is the only value that you don't want to wait for. Therefore, you cannot use the equal sign operator to determine whether a value is NaN, but there is a global function isNaN() to do this.
Copy the codeThe code is as follows:

> isNaN(NaN)
true

Kit CambridgePoint outA problem with isNaN(): It will implicitly convert its parameters into numbers, so even if the parameters are strings that cannot be converted into numbers, it will returntrue (converted to NaN):

Copy the codeThe code is as follows:

> Number("xyz")
NaN
> isNaN("xyz")
true


For the same reason, isNaN also returns true for many other objects:
Copy the codeThe code is as follows:

> Number({})
NaN
> isNaN({})
true

> Number(["xzy"])
NaN
> isNaN(["xzy"])
true

The same is true for rewriting the valueOf method:
Copy the codeThe code is as follows:

> var obj = { valueOf: function () { return NaN } };
> Number(obj)
NaN
> isNaN(obj)
true

Therefore, you can use NaN as the only value that satisfies the (x !== x) inequality to write your own isNaN function, so that there will be no problems mentioned above:
Copy the codeThe code is as follows:

function myIsNaN(x) {
return x !== x;
}

Currently, a revised version of isNaN method () has been added to ECMAScript 6 (Translator's note: Firefox has been implemented). This method implemented by Crockford is easier to understand than the above myIsNaN. The core code is as follows:
Copy the codeThe code is as follows:

= function (value) {
return typeof value === 'number' && isNaN(value);
};




Using 0 as the divisor will generate another special value Infinity:
Copy the codeThe code is as follows:

> 3/0
Infinity

You can't guess the calculation results of positive infinity or negative infinity for granted:
Copy the codeThe code is as follows:

>Infinity - Infinity
NaN

A value larger than infinity is still infinity:

Copy the codeThe code is as follows:

> Infinity + Infinity
Infinity> 5 * Infinity
Infinity


3. Reference

What is {} + {} in JavaScript?