Episode 24 of 46

NaN (Not a Number) in JavaScript

Understand NaN — what it is, why it exists, and how to handle it.

NaN stands for Not a Number. It represents a failed numeric operation. Despite the name, typeof NaN is "number"!

When NaN Appears

console.log(0 / 0);              // NaN
console.log("hello" * 2);        // NaN
console.log(parseInt("abc"));    // NaN
console.log(Math.sqrt(-1));      // NaN
console.log(undefined + 1);      // NaN

The Weird Thing About NaN

// NaN is NOT equal to anything — not even itself!
console.log(NaN === NaN);   // false
console.log(NaN == NaN);    // false

Checking for NaN

// Global isNaN() — converts to number first (can be misleading)
isNaN("hello");    // true (converts "hello" to NaN)
isNaN("42");       // false (converts "42" to 42)
isNaN(undefined);  // true

// Number.isNaN() — strict check (recommended)
Number.isNaN(NaN);       // true
Number.isNaN("hello");   // false (doesn't convert)
Number.isNaN(undefined); // false

Handling NaN in Practice

function safeParseInt(value) {
    let result = parseInt(value);
    if (Number.isNaN(result)) {
        return 0;  // Default value
    }
    return result;
}

console.log(safeParseInt("42"));    // 42
console.log(safeParseInt("abc"));   // 0
console.log(safeParseInt(""));      // 0

NaN is Contagious

// Any operation with NaN produces NaN
console.log(NaN + 5);     // NaN
console.log(NaN * 10);    // NaN
console.log(NaN > 0);     // false
console.log(NaN < 0);     // false