What is NaN in JavaScript? A Complete Not a Number Guide

Understand what NaN means in JavaScript, why it exists, how it behaves differently from every other value, and how to detect and handle it correctly in your code.

JavaScriptbeginner
9 min read

NaN stands for "Not a Number" and is one of the most misunderstood values in JavaScript. It appears when a mathematical operation fails to produce a valid numeric result, yet typeof NaN returns "number". It is the only value in JavaScript that is not equal to itself. And it shows up in production code far more often than most developers expect.

Think of NaN like a receipt from a calculator that tried to compute something impossible. The calculator could not produce an answer, but it still needed to give you something back. Instead of crashing, it hands you a receipt labeled "NaN" that says: "I tried to do math, but the inputs did not make sense." That receipt is still technically a number-type value (it came from the calculator), but it does not represent any actual numeric quantity.

This guide explains exactly what NaN is, why it behaves the way it does, every operation that produces it, and how to detect and handle it reliably.

How NaN is Created

NaN appears whenever JavaScript attempts a numeric operation that cannot produce a meaningful number. Here are the most common operations that produce NaN:

javascriptjavascript
// Parsing non-numeric strings
console.log(parseInt("hello"));     // NaN
console.log(parseFloat("abc"));     // NaN
console.log(Number("not-a-number")); // NaN
 
// Invalid math operations
console.log(0 / 0);                 // NaN
console.log(Math.sqrt(-1));         // NaN
console.log(Math.log(-1));          // NaN
 
// Arithmetic with undefined
console.log(undefined + 1);         // NaN
console.log(undefined * 5);         // NaN
 
// Arithmetic with non-numeric strings
console.log("hello" * 2);           // NaN
console.log("abc" - 1);             // NaN
 
// Operations that LOOK like they should produce NaN but don't
console.log("5" * 2);               // 10 (implicit conversion works)
console.log(null + 1);              // 1 (null converts to 0)
console.log(true + 1);              // 2 (true converts to 1)
console.log("" + 1);                // "1" (string concatenation, not NaN)
ExpressionResultWhy
parseInt("hello")NaNString has no numeric prefix
Number("abc")NaNEntire string is non-numeric
0 / 0NaNZero divided by zero is mathematically undefined
Math.sqrt(-1)NaNSquare root of negative number is not real
undefined + 1NaNundefined cannot convert to a number
"hello" * 2NaNString cannot convert to a number for multiplication
Infinity - InfinityNaNSubtracting infinity from infinity is undefined

Why typeof NaN Returns "number"

One of the most confusing things about NaN is that the typeof operator returns "number" for it:

javascriptjavascript
console.log(typeof NaN); // "number"

This seems contradictory since NaN literally means "Not a Number." The explanation lies in the IEEE 754 floating-point specification, which JavaScript uses for all numeric values. According to IEEE 754, NaN is a special floating-point value that represents an undefined or unrepresentable mathematical result. It occupies a specific bit pattern in the number format, making it technically a member of the number type.

In practical terms: NaN is not "not a number" in the JavaScript type system. It is "the number that represents an impossible result."

javascriptjavascript
// NaN lives in the Number type alongside these values
console.log(typeof 42);        // "number"
console.log(typeof 3.14);      // "number"  
console.log(typeof Infinity);  // "number"
console.log(typeof -Infinity); // "number"
console.log(typeof NaN);       // "number" (same type, special value)

NaN is Not Equal to Itself

NaN is the only value in JavaScript where strict equality with itself returns false:

javascriptjavascript
console.log(NaN === NaN); // false
console.log(NaN == NaN);  // false
console.log(NaN !== NaN); // true

This behavior is mandated by the IEEE 754 specification and is consistent across all programming languages that implement it (C, C++, Java, Python, etc.). The reasoning is that NaN could represent any number of different "impossible" results, and two impossible results should not be considered equal.

javascriptjavascript
// Two different operations that produce NaN
const a = 0 / 0;           // NaN
const b = Math.sqrt(-1);   // NaN
 
// These are both NaN, but they represent different failures
console.log(a === b); // false
 
// This behavior has practical implications
const values = [1, 2, NaN, 4];
console.log(values.indexOf(NaN)); // -1 (indexOf uses === comparison)
Never Compare with === to Check for NaN

Since NaN !== NaN, you cannot use equality operator to detect NaN. Always use Number.isNaN() or the global isNaN() function. The equality comparison value === NaN will always return false, even when value is actually NaN.

How to Detect NaN

JavaScript provides two functions for detecting NaN, and they behave differently:

Number.isNaN() returns true only when the value is actually NaN. It does not perform any type coercion:

javascriptjavascript
console.log(Number.isNaN(NaN));        // true
console.log(Number.isNaN(0 / 0));      // true
 
// Does NOT coerce the argument
console.log(Number.isNaN("hello"));    // false (string, not NaN)
console.log(Number.isNaN(undefined));  // false (undefined, not NaN)
console.log(Number.isNaN(null));       // false
console.log(Number.isNaN(true));       // false
console.log(Number.isNaN("NaN"));      // false (the string "NaN", not the value)

Global isNaN() (Use with Caution)

The global isNaN() function first coerces the value to a number, then checks if the result is NaN. This means it returns true for values that are not NaN but cannot be converted to a number:

javascriptjavascript
console.log(isNaN(NaN));        // true
console.log(isNaN(0 / 0));      // true
 
// These return true because coercion to Number produces NaN
console.log(isNaN("hello"));    // true (Number("hello") is NaN)
console.log(isNaN(undefined));  // true (Number(undefined) is NaN)
console.log(isNaN("NaN"));      // true (Number("NaN") is NaN)
 
// But these don't, because coercion succeeds
console.log(isNaN(null));       // false (Number(null) is 0)
console.log(isNaN(true));       // false (Number(true) is 1)
console.log(isNaN("42"));       // false (Number("42") is 42)

Comparison of NaN Detection Methods

MethodNaN"hello"undefinednull42
Number.isNaN()truefalsefalsefalsefalse
isNaN()truetruetruefalsefalse
value !== valuetruefalsefalsefalsefalse
Object.is(value, NaN)truefalsefalsefalsefalse
javascriptjavascript
// The self-inequality trick (clever but less readable)
function isNaNValue(value) {
  return value !== value;
}
 
console.log(isNaNValue(NaN));     // true
console.log(isNaNValue(42));      // false
console.log(isNaNValue("hello")); // false

NaN is Contagious

Once NaN enters a calculation, it propagates through every subsequent operation:

javascriptjavascript
const price = NaN;
const quantity = 5;
const tax = 0.08;
 
const subtotal = price * quantity;     // NaN
const taxAmount = subtotal * tax;      // NaN
const total = subtotal + taxAmount;    // NaN
 
console.log(total); // NaN (the original NaN infected everything)

This "contagious" behavior is actually useful because it prevents silent data corruption. Instead of producing a wrong but plausible number, NaN signals that something went wrong upstream. The key is to detect it early.

javascriptjavascript
// Validate inputs at the boundary to prevent NaN propagation
function calculateTotal(priceStr, quantityStr, taxRate) {
  const price = parseFloat(priceStr);
  const quantity = parseInt(quantityStr, 10);
 
  if (Number.isNaN(price)) {
    throw new Error(`Invalid price: "${priceStr}"`);
  }
  if (Number.isNaN(quantity)) {
    throw new Error(`Invalid quantity: "${quantityStr}"`);
  }
 
  return price * quantity * (1 + taxRate);
}
 
// Good input
console.log(calculateTotal("29.99", "3", 0.08)); // 97.1676
 
// Bad input caught early
try {
  calculateTotal("free", "3", 0.08);
} catch (e) {
  console.log(e.message); // 'Invalid price: "free"'
}

NaN in Arrays and Data Structures

NaN behaves unexpectedly with several array methods:

javascriptjavascript
const data = [1, 2, NaN, 4, NaN, 6];
 
// indexOf cannot find NaN (uses === comparison)
console.log(data.indexOf(NaN)); // -1
 
// includes CAN find NaN (uses SameValueZero algorithm)
console.log(data.includes(NaN)); // true
 
// filter with Number.isNaN works
const withoutNaN = data.filter(x => !Number.isNaN(x));
console.log(withoutNaN); // [1, 2, 4, 6]
 
// Set treats all NaN values as the same (SameValueZero)
const uniqueSet = new Set([NaN, NaN, NaN]);
console.log(uniqueSet.size); // 1
console.log([...uniqueSet]); // [NaN]
javascriptjavascript
// Sorting with NaN produces inconsistent results
const numbers = [3, NaN, 1, NaN, 2];
numbers.sort((a, b) => a - b);
// Result is implementation-dependent because NaN comparisons return false
console.log(numbers); // Order varies by engine
 
// Always filter out NaN before sorting
const cleanNumbers = numbers.filter(n => !Number.isNaN(n));
cleanNumbers.sort((a, b) => a - b);
console.log(cleanNumbers); // [1, 2, 3]

Best Practices

Handling NaN in Production Code

These practices prevent NaN from silently corrupting calculations and displaying broken values in your UI.

Validate numeric inputs at the boundary. Every time you parse user input, API response data, or query parameters into numbers, immediately check for NaN. Catching it at the entry point is far easier than debugging it three function calls later.

Use Number.isNaN() over the global isNaN(). The global isNaN() coerces its argument, leading to false positives with strings and undefined. Number.isNaN() only returns true for actual NaN values, making it predictable and safe.

Provide fallback values for NaN results. When a numeric operation might fail, use the logical OR pattern or nullish coalescing with a NaN check to provide a sensible default:

javascriptjavascript
function parseAge(input) {
  const age = parseInt(input, 10);
  return Number.isNaN(age) ? 0 : age;
}

Never display NaN to users. If a calculation produces NaN, display a meaningful message instead. Users should see "Price unavailable" or "0.00", not "NaN" in your UI.

Filter NaN before aggregation. When computing sums, averages, or other aggregations on arrays that might contain NaN, always filter first. A single NaN in a reduce operation will poison the entire result.

Common Mistakes and How to Avoid Them

Watch Out for These Pitfalls

NaN bugs are notoriously hard to track down because NaN propagates silently through calculations without throwing errors.

Comparing NaN with === or ==. This is the most common NaN mistake. Since NaN !== NaN, equality comparisons always return false. Use Number.isNaN(value) instead:

javascriptjavascript
// Wrong
if (result === NaN) { /* never executes */ }
 
// Correct
if (Number.isNaN(result)) { /* works */ }

Using the global isNaN() for type checking. Global isNaN("hello") returns true because it coerces the string to a number first. If you want to know whether a value is specifically the NaN value, use Number.isNaN().

Forgetting to validate parseInt/parseFloat results. parseInt() and parseFloat() return NaN when they cannot parse the input. Always check the return value before using it in calculations.

Not handling NaN in JSON serialization. JSON.stringify(NaN) converts NaN to null, which means a round-trip through JSON loses the NaN information:

javascriptjavascript
const data = { score: NaN };
const json = JSON.stringify(data);
console.log(json); // '{"score":null}'
 
const parsed = JSON.parse(json);
console.log(parsed.score);                 // null (not NaN)
console.log(Number.isNaN(parsed.score));   // false

Next Steps

Learn to detect NaN with isNaN()

Practice using both Number.isNaN() and the global isNaN() to understand their different behaviors. The isNaN() function guide covers both in depth.

Understand undefined and null

NaN, undefined, and null are JavaScript's three "special" values. Learning how they differ and when each appears will help you handle edge cases confidently.

Build input validation for a form

Create a form that accepts numeric input (price, age, quantity) and validates each field with proper NaN detection before processing. This is the most common real-world scenario where NaN handling matters.

Practice with array operations

Create an array with mixed values (numbers, NaN, strings) and practice filtering, mapping, and reducing while handling NaN correctly at each step.

Rune AI

Rune AI

Key Insights

  • NaN origin: NaN appears from failed number parsing, impossible math operations, and arithmetic with undefined
  • typeof paradox: typeof NaN returns "number" because NaN is an IEEE 754 floating-point special value
  • Self-inequality: NaN is the only JavaScript value where NaN !== NaN is true
  • Detection: use Number.isNaN() for reliable NaN checking; avoid the global isNaN() which has false positives
  • Propagation: NaN infects every subsequent calculation, so validate numeric inputs at the boundary before processing
RunePowered by Rune AI

Frequently Asked Questions

Why is NaN not equal to itself in JavaScript?

This behavior comes from the IEEE 754 floating-point specification, which JavaScript follows. NaN represents the result of an undefined mathematical operation, and since there are many different operations that produce NaN (0/0, sqrt(-1), parseInt("abc")), comparing two NaN values is like comparing two error conditions. The specification says they should not be considered equal because they might represent completely different failures.

What is the difference between NaN and undefined?

NaN is a numeric value that indicates a failed mathematical operation. `undefined` means [a variable](/tutorials/programming-languages/javascript/js-variables-guide-how-to-declare-and-use-them) has been declared but not assigned a value. They serve different purposes: NaN signals bad math, while undefined signals missing data. `typeof NaN` returns `"number"` and `typeof undefined` returns `"undefined"`. Both are falsy, but they are not interchangeable.

Does NaN equal false or null?

No. NaN is not equal to any value, including false, null, undefined, 0, and empty string. Both `NaN == false` and `NaN == null` return false. NaN is not even equal to itself. The only way to check for NaN is with `Number.isNaN()` or the global `isNaN()` function.

Can NaN be converted to a string?

Yes. `String(NaN)` returns the string `"NaN"`, and `NaN.toString()` also returns `"NaN"`. [Template literal](/tutorials/programming-languages/javascript/guide-to-javascript-template-literals-and-strings) handle it the same way: `` `${NaN}` `` produces `"NaN"`. This is why you should always validate numeric values before embedding them in UI strings, or your users will see "Your total is $NaN".

How do I remove NaN values from an array?

Use `Array.filter()` with `Number.isNaN()`: `array.filter(x => !Number.isNaN(x))`. This removes all NaN values while keeping everything else, including 0, false, null, and empty strings. Do not use `array.filter(x => x)` because that also removes 0 and empty strings.

Conclusion

NaN is JavaScript's way of signaling that a numeric operation produced no valid result. Its counterintuitive behaviors (typeof returns "number", it is not equal to itself, it propagates through calculations) all trace back to the IEEE 754 specification. The key to working with NaN reliably is detecting it early at input boundaries using Number.isNaN(), providing fallback values before it can propagate, and never displaying raw NaN to end users.