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.
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:
// 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)| Expression | Result | Why |
|---|---|---|
parseInt("hello") | NaN | String has no numeric prefix |
Number("abc") | NaN | Entire string is non-numeric |
0 / 0 | NaN | Zero divided by zero is mathematically undefined |
Math.sqrt(-1) | NaN | Square root of negative number is not real |
undefined + 1 | NaN | undefined cannot convert to a number |
"hello" * 2 | NaN | String cannot convert to a number for multiplication |
Infinity - Infinity | NaN | Subtracting 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:
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."
// 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:
console.log(NaN === NaN); // false
console.log(NaN == NaN); // false
console.log(NaN !== NaN); // trueThis 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.
// 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() (Recommended)
Number.isNaN() returns true only when the value is actually NaN. It does not perform any type coercion:
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:
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
| Method | NaN | "hello" | undefined | null | 42 |
|---|---|---|---|---|---|
Number.isNaN() | true | false | false | false | false |
isNaN() | true | true | true | false | false |
value !== value | true | false | false | false | false |
Object.is(value, NaN) | true | false | false | false | false |
// 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")); // falseNaN is Contagious
Once NaN enters a calculation, it propagates through every subsequent operation:
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.
// 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:
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]// 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:
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:
// 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:
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)); // falseNext 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
Key Insights
- NaN origin: NaN appears from failed number parsing, impossible math operations, and arithmetic with undefined
- typeof paradox:
typeof NaNreturns "number" because NaN is an IEEE 754 floating-point special value - Self-inequality: NaN is the only JavaScript value where
NaN !== NaNis true - Detection: use
Number.isNaN()for reliable NaN checking; avoid the globalisNaN()which has false positives - Propagation: NaN infects every subsequent calculation, so validate numeric inputs at the boundary before processing
Frequently Asked Questions
Why is NaN not equal to itself in JavaScript?
What is the difference between NaN and undefined?
Does NaN equal false or null?
Can NaN be converted to a string?
How do I remove NaN values from an array?
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.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.