Interview question
What is NaN and how do you check for it correctly? NaN क्या है और इसे सही तरीके से कैसे check करें?
Answer
NaN stands for 'Not-a-Number' but is of type 'number'. It's the only value in JavaScript that is not equal to itself!
// What produces NaN
const a = 0 / 0; // NaN
const b = parseInt('hello'); // NaN
const c = undefined + 5; // NaN
const d = Math.sqrt(-1); // NaN
// WRONG way to check for NaN
if (a == NaN) console.log('This will NEVER run!'); // Always false
if (a === NaN) console.log('This will NEVER run!'); // Always false
if (typeof a === 'number' && a != a) console.log('Hacky way'); // Works but ugly
// RIGHT way to check for NaN
if (isNaN(a)) console.log('Correct!'); // true
if (Number.isNaN(a)) console.log('Even better!'); // true - strict version
// Difference between isNaN and Number.isNaN
console.log(isNaN('hello')); // true (converts to number first)
console.log(Number.isNaN('hello')); // false (no type conversion)| Check method | Description | Type coercion? |
|---|---|---|
| NaN == NaN | WRONG - always false | N/A |
| isNaN() | Good, but coerces type | Yes |
| Number.isNaN() | BEST - strict, no coercion | No |
Interview tip: NaN !== NaN is one of the most famous JavaScript quirks. Always use Number.isNaN() for reliable checking. Mention that typeof NaN === 'number' (weird!).
NaN का मतलब 'Not-a-Number' है पर यह 'number' type का है। यह JavaScript में एकमात्र value है जो अपने आप के बराबर नहीं है!
// NaN क्या produce करता है
const a = 0 / 0; // NaN
const b = parseInt('hello'); // NaN
const c = undefined + 5; // NaN
// गलत तरीका
if (a == NaN) console.log('यह कभी नहीं चलेगा'); // Always false
if (a === NaN) console.log('यह कभी नहीं चलेगा'); // Always false
// सही तरीका
if (isNaN(a)) console.log('सही है'); // true
if (Number.isNaN(a)) console.log('और भी बेहतर'); // true
// isNaN vs Number.isNaN में अंतर
console.log(isNaN('hello')); // true (convert करता है)
console.log(Number.isNaN('hello')); // false (convert नहीं करता)| Check method | Description | Type coercion? |
|---|---|---|
| NaN == NaN | गलत - हमेशा false | N/A |
| isNaN() | अच्छा, पर coerces | हाँ |
| Number.isNaN() | सबसे अच्छा - strict | नहीं |
इंटरव्यू टिप: NaN !== NaN एक famous JavaScript quirk है। हमेशा Number.isNaN() use करें। typeof NaN === 'number' का ज़िक्र करें।
Was this answer clear?