Beginner LevelJavaScript & TypeScript
What is NaN, how is it checked, and why does NaN !== NaN?
❓ Interview Prompt: Explain NaN (Not-a-Number), IEEE 754 floating point standard rules, Number.isNaN() vs global isNaN().
NaN stands for "Not-a-Number", representing an unrepresentable or undefined numerical calculation result (e.g., 0 / 0 or Math.sqrt(-1)).
The NaN Paradox (NaN !== NaN):
Per the IEEE 754 floating-point specification, NaN is the only value in JavaScript that is not equal to itself:
•
NaN === NaN returns false!Checking for NaN:
•
❌ Global
isNaN(val): Performs type coercion first! isNaN('hello') returns true (string coerced to NaN).•
✅
Number.isNaN(val): Checks if the value is strictly NaN without coercion.•
✅
Object.is(val, NaN): Returns true.Code Implementation Example
javascript
console.log(NaN === NaN); // false (!)
// ❌ Global isNaN coerces strings to NaN
isNaN('hello'); // true (coerced 'hello' -> NaN)
isNaN(undefined); // true (coerced undefined -> NaN)
// ✅ Number.isNaN checks without coercion
Number.isNaN('hello'); // false (it's a string, not NaN!)
Number.isNaN(0 / 0); // true
Number.isNaN(NaN); // true
// Self-equality trick to check NaN
function isRealNaN(value) {
return value !== value; // Only true for NaN!
}💡The NaN self-inequality quirk and global isNaN vs Number.isNaN comparison.
🎯 Interview Key Takeaway
NaN is never equal to anything, including itself. Always use Number.isNaN() instead of global isNaN().
#NaN#Numbers#Coercion#Beginner
Back to all JavaScript & TypeScript Questions→