Emmanuel Akinfulubi

JavaScriptValidation

Check if a value is a number in JavaScript

Intermediate · 3 min read

Prices, ages, quantities and scores all have to be numbers before you can add them up. Checking for that sounds simple, but "is it a number?" can mean three different things, and the obvious check lets through two values that will break any sum they touch.

In this tutorial you will write three small checks: one for the type, one for a number you can actually do arithmetic with, and one for text typed into a form. You should know what typeof does and have seen NaN (the "Not a Number" value). Everything else is explained as we go.

Two numbers that aren't usable

JavaScript has two special values that have the type 'number' but behave nothing like normal numbers:

JavaScript

console.log(typeof NaN);      // number
console.log(typeof Infinity); // number
console.log(NaN + 1);         // NaN
console.log(Infinity - Infinity); // NaN

NaN means a calculation failed. Infinity is what you get from things like 1 / 0. Once either one gets into your data, the results turn into NaN or Infinity as well. A value that is a normal number, not NaN and not Infinity, is called finite.

Converting versus checking

Some built-in functions convert their argument before they look at it. Others don't. That difference matters a lot here:

JavaScript

console.log(Number('5'));   // 5
console.log(Number(''));    // 0
console.log(Number('   ')); // 0
console.log(Number('abc')); // NaN

Number() turns a value into a number. The empty string and a string of spaces both become 0, which is a trap for form input.

Here is the exercise. Have a go on your own if you like, or read on and we will build it together.

5 Is the value a number?

fair

Check whether a value is a number. Decide first what you actually mean, because NaN and Infinity both pass typeof v === 'number'.

Stuck? Three hints, smallest first
  1. 1. typeof v === ‘number’ is true for NaN and for Infinity.
  2. 2. Number.isFinite is usually the check you want: a real, usable number.
  3. 3. The global isFinite converts first, so isFinite(‘5’) is true. Number.isFinite does not.

Step 1: the type check

The literal reading of the question is "is the type 'number'?":

Step 1

const isNumberType = (v) => typeof v === 'number';

console.log(isNumberType(42));       // true
console.log(isNumberType('5'));      // false
console.log(isNumberType(NaN));      // true
console.log(isNumberType(Infinity)); // true

It correctly refuses the string '5'. But it accepts NaN and Infinity, which is rarely what you want.

Step 2: a number you can use

Number.isFinite(v) is true only for a real number that is not NaN and not Infinity. It doesn't convert anything:

Step 2

const isUsableNumber = (v) => typeof v === 'number' && Number.isFinite(v);

console.log(isUsableNumber(42));       // true
console.log(isUsableNumber(0));        // true
console.log(isUsableNumber(-3.5));     // true
console.log(isUsableNumber(NaN));      // false
console.log(isUsableNumber(Infinity)); // false
console.log(isUsableNumber('5'));      // false

Number.isFinite already returns false for anything that isn't a number, so the typeof part isn't strictly needed. It is there to make the intention obvious to the next reader.

A number wrapped in an object with new Number(5) is refused too, because its type is 'object':

JavaScript

console.log(typeof new Number(5));          // object
console.log(Number.isFinite(new Number(5))); // false

Step 3: the global isFinite wrong turn

There is also an older global function called isFinite, without Number. in front. It converts first:

JavaScript

console.log(isFinite('5'));   // true
console.log(isFinite(''));    // true
console.log(isFinite('  '));  // true
console.log(isFinite([]));    // true
console.log(isFinite(null));  // true
console.log(isFinite(true));  // true

console.log(Number.isFinite('5')); // false

Every one of those converts to a finite number ('', [] and null all become 0, and true becomes 1), so the global function says yes. Use Number.isFinite.

Step 4: checking text from a form

Values from an input box are always strings, even when the person typed digits. So for form input you need a third check: "is this string a number?"

JavaScript

const tryIt = (s) => typeof s === 'string' && Number.isFinite(Number(s));

console.log(tryIt('5'));   // true
console.log(tryIt('abc')); // false
console.log(tryIt('   ')); // true, but the field is blank

A field of spaces becomes 0, so it passes as the number zero. We need to refuse blank text before converting. s.trim() removes spaces from both ends, so a blank field becomes '':

Step 4

const isNumericString = (s) =>
  typeof s === 'string' && s.trim() !== '' && Number.isFinite(Number(s));

console.log(isNumericString('5'));    // true
console.log(isNumericString('-3.5')); // true
console.log(isNumericString(''));     // false
console.log(isNumericString('   '));  // false
console.log(isNumericString('abc'));  // false
console.log(isNumericString('12abc')); // false

Number('12abc') is NaN, so mixed text is refused as well.

The full solution

The panel has all three checks and prints a table comparing the global isFinite with Number.isFinite. Press Run to see where they disagree.

The answer

// Literally "is of type number" — includes NaN and Infinity.
const isNumberType = (v) => typeof v === 'number';

// What people usually mean: a number you can do arithmetic with.
const isUsableNumber = (v) => typeof v === 'number' && Number.isFinite(v);

// For text input: is this string a number? Note the trim guard, because
// Number('') and Number('   ') are both 0.
const isNumericString = (s) =>
  typeof s === 'string' && s.trim() !== '' && Number.isFinite(Number(s));

const wrapped = new Number(5);

console.log('typeof NaN      :', typeof NaN, '   isUsable:', isUsableNumber(NaN));
console.log('typeof Infinity :', typeof Infinity, '   isUsable:', isUsableNumber(Infinity));
console.log("typeof '5'      :", typeof '5', '   isUsable:', isUsableNumber('5'));
console.log('new Number(5)   :', typeof wrapped, '<- an object');
console.log('--- global isFinite converts, Number.isFinite does not ---');
for (const v of ['5', '', '  ', [], null, true]) {
  console.log(JSON.stringify(v).padEnd(6), 'isFinite:', String(isFinite(v)).padEnd(6), 'Number.isFinite:', Number.isFinite(v));
}

Output


      
18 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 18 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

18 checks

test('42 is a number', isUsableNumber(42), true);
test('so is 0', isUsableNumber(0), true);
test('and a decimal', isUsableNumber(-3.5), true);
test('NaN has type number', isNumberType(NaN), true);
test('but it is not usable', isUsableNumber(NaN), false);
test('Infinity has type number too', isNumberType(Infinity), true);
test('and is also not usable', isUsableNumber(Infinity), false);
test('the string "5" is not a number', isUsableNumber('5'), false);
test('a wrapper object is not either', isUsableNumber(wrapped), false);
test('the global isFinite is fooled by a numeric string', isFinite('5'), true);
test('Number.isFinite is not', Number.isFinite('5'), false);
test('the global is even fooled by the empty string', isFinite(''), true);
test('because Number("") is 0', Number(''), 0);
test('the string check accepts a numeric string', isNumericString('5'), true);
test('and a decimal one', isNumericString('-3.5'), true);
test('but refuses an empty field', isNumericString(''), false);
test('and a field of only spaces', isNumericString('   '), false);
test('and text', isNumericString('abc'), false);

"Is it a number" is three different questions. typeof answers the type question and lets NaN and Infinity through — both of which will poison any arithmetic downstream. Number.isFinite answers the useful one. And validating text from a form is a third thing entirely, where the trim() !== '' guard is essential: Number(' ') is 0, so a field containing only spaces otherwise validates as the number zero.

Common mistakes

  • Stopping at typeof v === 'number'. NaN and Infinity pass, and they spoil every calculation after them.
  • Using the global isFinite. It converts first, so isFinite('') is true. Use Number.isFinite.
  • Forgetting the blank check on form text. Number(' ') is 0, so an empty field looks like a valid zero.

Try it yourself

  1. Write isPositiveNumber(v) that accepts only usable numbers greater than zero.
  2. Try isNumericString('1e3') and isNumericString('0x10'). Both pass. Decide whether a price field should accept them.
  3. Write readQuantity(text) that returns the number for valid text and null otherwise.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.