In JavaScript, NaN
is a property of the global Object
. In other words, it is a variable available in the Global scope.
It stands for Not-A-Number but interestingly, its type is number
.
console.log(typeOf NaN); // "number"
It is used to denote an object that is not or does not compute to a number
, in a context when number
operations are applied on that object.
Another interesting fact about NaN
is, it never equals to itself. So NaN == NaN
or NaN === NaN
is always false
.
console.log(NaN == NaN); // false
console.log(NaN === NaN); // false
Testing for NaN
Since a NaN
is never equal to another NaN
, a self-comparison of a value makes it the most reliable way to test if the value is NaN
.
function isThisNaN(value) { return value !== value };
isThisNaN(1); // false
isThisNaN(NaN); // true
isThisNaN(Number.NaN); // true
isThisNaN('NaN'); // false
Other ways to test if an object is NaN
are using the isNaN()
global method and Number.isNaN()
.
console.log(isNaN('hi')); //true
console.log(isNaN('4'); // false
In the two examples above, isNaN()
waits for type coercion on the string
before it makes the comparison. In the first case with 'hi'
, the string
is coerced to number
, which then evaluates to NaN
because it doesn't return a number. In the second case with '4'
, it gets evaluated to a number
so it is not a NaN
. So using isNaN()
is not very reliable to test for NaN
In contrast, Number.isNaN()
tests the current value:
console.log(Number.isNaN('hi')); // false
console.log(Number.isNaN('4')); // false (this time because
// it's a string in the
// context of a Number method)
Type coercion is not present with Number.isNaN()
. Instead, it compares the string directly. In the code above, both 'hi'
and '4'
are string
s and therefore not NaN
in the context of a Number
method. This makes Number.isNaN()
more reliable than isNaN()
while testing for NaN
values.
References
Top comments (1)
Thanks!
I never used
Object.is()
, but this is essentially the same thing asNumber.isNaN()
. I'm a bit skeptical about bothNumber.isNaN()
andObject.is()
because they returntrue
if we compare two diiferentNaN
s, whereas comparing twoNaN
s with equality operators returnfalse
.I think basing the comparison on
NaN
never being equal to anotherNaN
makes it interesting.What's your take?