What is NaN in JavaScript?
In JavaScript, NaN stands for "Not-a-Number." It is a special value used to represent something that is not a valid number, even though it is of type number.
What causes NaN?
Math operations that don't make sense result in NaN. For example, dividing 0 by 0 or trying to convert a non-numeric string to a number.
console.log(0 / 0); // NaN
console.log(Number("hello")); // NaN
Type of NaN:
Even though NaN means "Not-a-Number", its type is still number (which is kind of ironic).
console.log(typeof NaN); // "number"
How to check for NaN:
You can't use == or === to check for NaN because NaN is never equal to itself.
console.log(NaN === NaN); // false
Instead, use isNaN() to check if a value is NaN:
console.log(isNaN(NaN)); // true
console.log(isNaN("hello")); // true
console.log(isNaN(123)); // false
ES6+ (New way to check for NaN):
There’s also a better way to check for NaN using Number.isNaN(), which is more accurate:
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN("hello")); // false (because "hello" isn't even a number)
Conclusion:
Basically, NaN is a weird value that tells you something went wrong with a number operation. But it still belongs to the number type, just not a valid number!

Leave a Comment