NaN — Not a Number
NaN (Not a Number)
Section titled “NaN (Not a Number)”Introduction
Section titled “Introduction”NaN is a special numeric value representing the result of an invalid or undefined mathematical operation. Despite its name, typeof NaN is 'number'.
Why Do We Need This?
Section titled “Why Do We Need This?”NaN appears when calculations fail. Knowing how to detect and handle NaN prevents silent bugs from propagating through your code.
Real World Story
Section titled “Real World Story”NaN is like a corrupted measurement. The reading says “Not a Measurement” but it’s still in the measurement column. If you don’t check for it, your averages will be wrong.
Visual Explanation
Section titled “Visual Explanation”flowchart TD Operation["0 / 0"] Parse["parseInt('abc')"] Math["Math.sqrt(-1)"] Coercion["Number(undefined)"]
Operation --> NaN Parse --> NaN Math --> NaN Coercion --> NaN
NaN --> Problem["NaN propagates through calculations"] Problem --> Result["Any operation with NaN returns NaN"]How NaN Occurs
Section titled “How NaN Occurs”0 / 0; // NaNparseInt('abc'); // NaNMath.sqrt(-1); // NaNNumber(undefined); // NaNNaN + 5; // NaN — propagates!The Unique Property
Section titled “The Unique Property”NaN is the only value in JavaScript that is not equal to itself:
NaN === NaN; // false — unique!NaN == NaN; // falseChecking for NaN
Section titled “Checking for NaN”// ✅ CorrectNumber.isNaN(NaN); // trueNumber.isNaN('abc'); // false — doesn't coerceNumber.isNaN(NaN + 5); // true
// ❌ Wrong — coerces firstisNaN('abc'); // true — because Number('abc') is NaNisNaN('123'); // false
// ✅ Alternativefunction isValueNaN(value) { return typeof value === 'number' && isNaN(value);}Best Practices
Section titled “Best Practices”- Always use
Number.isNaN()instead of globalisNaN() - Validate numeric inputs before performing operations
- Use fallback values for failed calculations
Summary
Section titled “Summary”NaNis a number type representing invalid mathNaN !== NaN— it’s not equal to itself- Use
Number.isNaN()for reliable checking - NaN propagates through all arithmetic operations