What is a NaN?
Level: Beginner
In JavaScript NaN
stands for Not a Number. Its a primitive value that is used to represent a non-number value within the number type. So in reality, NaN
is both a number, and not.
The value NaN
is accessible both as a global and as a property of Number
.
console.log(NaN); // NaN
console.log(Number.NaN); // NaN
console.log(typeof NaN); // number
Any time you perform a numeric operation that can’t resolve into a number, you’ll get NaN
as a result.
console.log(1 * 'x'); // NaN
console.log(0/0); // NaN
console.log(Math.sqrt(-1)); // NaN
If you try to convert a value that can’t be turned into a number, you’ll also get a NaN
value in return.
console.log(Number('x')); // NaN
console.log(+{}); // NaN
The value NaN
has a peculiar behavior where its not equal to itself.
console.log(NaN === NaN); // false
To see if something is NaN
, instead of comparing it to NaN
, you can use an isNaN()
function. There are also two of these, one global and one in Number
, though they work slightly differently. The global isNaN()
will first try to convert a value to a number and then see if the result is NaN
whereas Number.isNaN()
will check specifically to see if the value its given is the value NaN
.
console.log(isNaN(NaN)); // true
console.log(isNaN('1')); // false
console.log(isNaN('x')); // true
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN('1')); // false
console.log(Number.isNaN('x')); // false
More info: