Number.isInteger, isFinite and isNaN in JavaScript
Beginner · 3 min read
Before you do math on a value, you often need to check it. Is it a whole number? Is it a real, finite number? Did a calculation go wrong and produce NaN? Form validation, quantity fields and API checks all ask these questions.
JavaScript gives you Number.isInteger, Number.isFinite and Number.isNaN. It also has two older functions, isNaN and isFinite, without the Number. in front, and they behave differently. In this tutorial you will try all of them and see why the Number. versions are the ones to use. You need to know typeof and ===.
What NaN is
NaN stands for "Not a Number". It is what you get when a calculation has no sensible numeric answer:
console.log(0 / 0); // NaN
console.log(Number('abc')); // NaN
console.log(typeof NaN); // number
The last line surprises people: NaN is itself of type number. It is a special number value that means "this calculation failed".
Coercion
Coercion means JavaScript converting a value from one type to another for you, for example turning the string '42' into the number 42. Some checks coerce first and some don't. That one difference is the whole story of this exercise.
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
17 Number.isInteger, isFinite and isNaN
easyTest whether a value is a whole number, a finite number, or NaN. Then show what the global isNaN and isFinite do that the Number. versions refuse to.
Stuck? Three hints, smallest first
- 1. The
Number.methods do no coercion: a string is never a number to them. - 2. The global
isNaN(‘abc’)istruebecause it converts first. - 3.
NaN === NaNisfalse, which is why a dedicated test exists at all.
Step 1: is it a whole number?
console.log(Number.isInteger(5)); // true
console.log(Number.isInteger(5.0)); // true
console.log(Number.isInteger(5.5)); // false
5.0 is an integer because, in JavaScript, 5 and 5.0 are the same value. There is only one number type, so there is no way to ask "was this written with a decimal point?".
Step 2: text is never a number
console.log(Number.isInteger('5')); // false
console.log(Number.isFinite('42')); // false
console.log(Number.isNaN('abc')); // false
The Number. methods don't coerce. A string is a string, so it is never an integer and never finite. And it isn't NaN either: 'abc' is text, not the special NaN number value.
Step 3: the older global versions
Now try the functions without Number. in front:
console.log(isNaN('abc')); // true
console.log(isFinite('42')); // true
console.log(isNaN('')); // false
These coerce first. isNaN('abc') turns 'abc' into a number, gets NaN, and says true. isFinite('42') turns '42' into 42 and says true.
The last line is the trap. An empty string converts to 0, so isNaN('') says it is a fine number. If you used that to validate a form field, an empty field would pass.
Put side by side:
console.log([isNaN('abc'), Number.isNaN('abc')]); // [ true, false ]
console.log([isFinite('42'), Number.isFinite('42')]); // [ true, false ]
Prefer the Number. versions. They answer "is this value already a number of this kind?", which is what you usually want. If you need to accept text, convert it yourself first with Number(value), so the conversion is visible in your code.
Step 4: why NaN needs its own test
You might expect to check for NaN with ===. That doesn't work:
console.log(NaN === NaN); // false
NaN is the only value in JavaScript that isn't equal to itself. So x === NaN is always false, whatever x is. That is why Number.isNaN exists:
console.log(Number.isNaN(0 / 0)); // true
console.log(Object.is(NaN, NaN)); // true
Object.is is a stricter comparison that does see NaN as equal to NaN. Either works; Number.isNaN reads more clearly.
Step 5: a small validator
Putting it together, here is a check for a quantity field that must be a whole number:
const isQuantity = (text) => text.trim() !== '' && Number.isInteger(Number(text));
console.log(isQuantity('3')); // true
console.log(isQuantity('3.5')); // false
console.log(isQuantity('')); // false
console.log(isQuantity('abc')); // false
The trim() !== '' part rejects empty and space-only input, because Number('') is 0. Then Number converts the text, and Number.isInteger checks the result, which also rejects NaN.
The full solution
The answer panel tests whole numbers, decimals and strings, compares the global isNaN and isFinite with the Number. versions, and shows that NaN isn't equal to itself. The checks underneath confirm each result. Press Run to see the output.
console.log('isInteger(5) :', Number.isInteger(5));
console.log('isInteger(5.0) :', Number.isInteger(5.0), '<- there is no separate float type');
console.log('isInteger(5.5) :', Number.isInteger(5.5));
console.log("isInteger('5') :", Number.isInteger('5'), '<- a string is not a number');
console.log("isNaN('abc') :", isNaN('abc'), 'against Number.isNaN:', Number.isNaN('abc'));
console.log("isFinite('42') :", isFinite('42'), 'against Number.isFinite:', Number.isFinite('42'));
console.log('NaN === NaN :', NaN === NaN);
console.log('Object.is(NaN,NaN):', Object.is(NaN, NaN));
Output
9 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 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a whole number is an integer', Number.isInteger(5), true);
test('and so is 5.0, since the two are the same value', Number.isInteger(5.0), true);
test('5.5 is not', Number.isInteger(5.5), false);
test('a numeric string is not a number to these methods', Number.isInteger('5'), false);
test('the global isNaN coerces first, Number.isNaN does not', [isNaN('abc'), Number.isNaN('abc')], [true, false]);
test('the same split applies to isFinite', [isFinite('42'), Number.isFinite('42')], [true, false]);
test('NaN is the one value not equal to itself', NaN === NaN, false);
test('so this is how you detect it', Number.isNaN(0 / 0), true);
test('or with Object.is, which does see it', Object.is(NaN, NaN), true);
Prefer the Number. methods. The globals were specified before undefined was even reliable and they coerce, so isNaN('') is false — an empty string converts to 0 — while isNaN('abc') is true. That is a type conversion masquerading as a numeric test, and it turns a validation bug into a silent pass.
Number.isInteger(5.0) being true is not a rounding: JavaScript has one numeric type, and 5.0 and 5 are the same double. There is no way to ask "was this written with a decimal point".
Common mistakes
- Testing
x === NaN. It is alwaysfalse. UseNumber.isNaN(x). - Validating input with the global
isNaN.isNaN('')isfalse, so an empty field passes. UseNumber.isNaNafter an explicitNumber(text), and check for empty text. - Expecting
Number.isInteger('5')to betrue. TheNumber.methods never convert strings. Convert first.
Try it yourself
- Predict
Number.isFinite(Infinity),Number.isFinite(NaN)andNumber.isFinite(1e308), then run them. - Extend
isQuantityso it also rejects negative numbers. - Run
isNaN(' ')andisNaN('12px'). Explain each result in terms of what the text converts to.