Check if a value is NaN in JavaScript
Intermediate · 3 min read
NaN stands for "Not a Number". It is what JavaScript gives you when a calculation can't produce a real number, for example when you turn the text 'abc' into a number. If a NaN slips into a price, a total or a chart, every sum it touches becomes NaN too, so catching it early matters.
In this tutorial you will learn to detect NaN correctly. That sounds like one line of code, and it is, but the obvious line is wrong and the old built-in helper answers a different question. You only need to know what === does.
Where NaN comes from
NaN appears whenever number work fails:
console.log(Number('abc')); // NaN
console.log(0 / 0); // NaN
console.log(Math.sqrt(-1)); // NaN
console.log(parseInt('abc')); // NaN
console.log(typeof NaN); // number
The last line surprises everyone. "Not a Number" has the type 'number'. It is a special number value that means "this calculation broke". So a typeof check lets it straight through.
The value that isn't equal to itself
Every value in JavaScript is equal to itself, except one:
console.log(1 === 1); // true
console.log(NaN === NaN); // false
This comes from IEEE 754, the standard way computers store numbers like 0.5. Most languages follow it, so they behave the same. It is also why the obvious check fails.
Here is the exercise. Try it on your own first if you like, or read on and we will build it together.
3 Is the value NaN?
fairDetect the value NaN. This is harder than it sounds: NaN is not equal to itself, and the old global isNaN answers a different question than the one you asked.
Stuck? Three hints, smallest first
- 1.
NaN === NaNisfalse. It is the only value in the language not equal to itself. - 2. The global
isNaN(v)convertsvto a number first, soisNaN(‘abc’)istrue. - 3.
Number.isNaNdoes no conversion, andv !== vis the same test without any function call.
Step 1: the obvious check
The first thing most people write is a comparison with NaN:
const isNaNWrong = (v) => v === NaN;
console.log(isNaNWrong(NaN)); // false
console.log(isNaNWrong(Number('abc'))); // false
It returns false every time, because nothing is ever === to NaN, not even NaN.
Step 2: the old global isNaN
JavaScript has a global function called isNaN. It looks like exactly what we want:
console.log(isNaN(NaN)); // true
console.log(isNaN('abc')); // true
console.log(isNaN(undefined)); // true
console.log(isNaN({})); // true
But 'abc' is a string, not NaN. The global isNaN first converts its argument to a number, and then asks if the result is NaN. So it really answers "would this become NaN if I turned it into a number?". That is a different question.
The conversion also runs the other way:
console.log(Number('')); // 0
console.log(isNaN('')); // false
console.log(isNaN([])); // false
An empty string converts to 0, and so does an empty array. Remember this one: an empty form field turns into the number zero, not NaN.
Step 3: Number.isNaN
Number.isNaN is the newer version. It does no conversion at all. It returns true only for the actual value NaN:
const isReallyNaN = (v) => Number.isNaN(v);
console.log(isReallyNaN(NaN)); // true
console.log(isReallyNaN(Number('abc'))); // true
console.log(isReallyNaN(0 / 0)); // true
console.log(isReallyNaN('abc')); // false
console.log(isReallyNaN(undefined)); // false
This is the check to use.
Step 4: the same test by hand
Since NaN is the only value not equal to itself, you can write the test without any function call:
const notItself = (v) => v !== v;
console.log(notItself(NaN)); // true
console.log(notItself(1)); // false
console.log(notItself('abc')); // false
const values = [NaN, 1, 'abc', undefined, null, {}, ''];
console.log(values.every((v) => notItself(v) === Number.isNaN(v))); // true
The last line checks that notItself and Number.isNaN agree on every value in the list. You will see v !== v in older code, so it helps to recognize it.
Object.is is one more way. It compares two values like ===, except that it treats NaN as equal to itself:
console.log(Object.is(NaN, NaN)); // true
The full solution
The panel has both checks and prints a table comparing the global isNaN with Number.isNaN for some tricky values. Press Run to see where they disagree.
// The correct check. No conversion: it is true only for actual NaN.
const isReallyNaN = (v) => Number.isNaN(v);
// The same test written by hand, and the reason it works: NaN is the only value
// in JavaScript that is not equal to itself.
const notItself = (v) => v !== v;
console.log('NaN === NaN :', NaN === NaN, '<- the whole problem');
console.log('typeof NaN :', typeof NaN, '<- it IS a number');
console.log('--- the global isNaN converts first, so it lies ---');
for (const v of ['abc', undefined, {}, '', [], '12abc']) {
console.log(String(JSON.stringify(v)).padEnd(8), 'isNaN:', String(isNaN(v)).padEnd(6), 'Number.isNaN:', Number.isNaN(v));
}
console.log('--- where NaN actually comes from ---');
console.log("Number('abc') =", Number('abc'));
console.log('0 / 0 =', 0 / 0);
console.log('Math.sqrt(-1) =', Math.sqrt(-1));
console.log("parseInt('abc')=", parseInt('abc'));
console.log("Number('') =", Number(''), '<- NOT NaN. Empty string is zero.');
Output
15 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 15 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('NaN is NaN', isReallyNaN(NaN), true);
test('and it is famously not equal to itself', NaN === NaN, false);
test('its type is number, which surprises people', typeof NaN, 'number');
test('the string "abc" is not NaN, it is a string', isReallyNaN('abc'), false);
test('but the global isNaN says true, because it converts first', isNaN('abc'), true);
test('the global also fails on undefined', isNaN(undefined), true);
test('while Number.isNaN is correct', Number.isNaN(undefined), false);
test('the empty string converts to 0, not NaN', Number(''), 0);
test('so isNaN("") is false', isNaN(''), false);
test('an empty array also converts to 0', isNaN([]), false);
test('v !== v is the same test', notItself(NaN), true);
test('and agrees on every case', [NaN, 1, 'abc', undefined, null, {}, ''].every((v) => notItself(v) === Number.isNaN(v)), true);
test('Number("abc") really is NaN', isReallyNaN(Number('abc')), true);
test('0 / 0 is NaN, not an error', isReallyNaN(0 / 0), true);
test('Object.is spots it as well', Object.is(NaN, NaN), true);
Three separate facts collide here. NaN has type 'number', so a typeof guard lets it through. It is not equal to itself, so v === NaN never matches anything. And the global isNaN means "is this not a number after conversion", which is a different question — isNaN('abc') is true even though 'abc' is a perfectly good string. Use Number.isNaN. And note Number('') is 0, so an empty form field sails through a naive numeric check as a valid zero.
Common mistakes
- Writing
v === NaN. It is alwaysfalse. UseNumber.isNaN(v). - Using the global
isNaN. It converts first, soisNaN('abc')istruefor a perfectly good string. - Trusting
typeof v === 'number'.NaNhas the type'number', so it passes.
Try it yourself
- Write
safeNumber(text)that returnsNumber(text), ornullwhen the result isNaN. - Call
safeNumber('')and explain why it returns0. Then change it to returnnullfor blank text. - Use
[3, NaN, 7, NaN].filter(...)to remove everyNaNfrom a list.