Is It a Number?

There are some surprises for the JS beginner in number checking. I take a crack at three good ways to go about doing this.

By Matthew Malinowski, 2013-05-28

For the Javascript beginner, checking to see if something is a number is some combination of really easy, pretty confusing, and dauntingly challenging. Once you understand the options you have available to you, you'll be identifying numbers like a seasoned pro.

When you're checking to see if something is a number in Javascript, your first idea might be to just check typeof and be done with it:

var isNumber = function(num) {
    return typeof num === 'number';

For some situations, this is all you need.

But, remember: there are three (perhaps unexpected, at least to me at first) values that have a typeof 'number': positive Infinity, negative Infinity, and NaN. If you want to exclude these values, you'll also need to check for finitude:

var isFiniteNumber = function(num) {
    return typeof num == 'number' && isFinite(num);

Or, if you have access to our above isNumber function and Aren't Repeating Yourself:

var isFiniteNumber = function(num) {
    return isNumber(num) && isFinite(num);

isFinite is going to exclude positive Infinity, negative Infinity, and NaN, none of which are finite. This function will reasonably tell you if something is a number... except if your input is formatted as a string.

What does this mean? isNumber(10) and isFiniteNumber(12) are both going to return true. isNumber('10') and isFiniteNumber('12') won't, because typeof num is going to be string in both cases.

In this case I might say: tough. Stuff that produces numbers that get fed to these functions should be producing them as numbers, not as numeric strings. But, I guess sometimes you just need to parse a string for numbers. Around version 1.7, jQuery added isNumeric , which does just this as it's checking the numberness of your input:

var isNumeric = function(num) {
    return !isNaN(parseFloat(num)) && isFinite(num);

isFinite is here for the same reason as I explained above, but that first part is new.

parseFloat parses a string for numeric characters and returns a floating point number. It's worth reading about on MDN. The tl;dr is:

"If [parseFloat()] encounters a character other than a sign (+ or -), numeral (0-9), a decimal point, or an exponent, it returns the value up to that point and ignores that character and all succeeding characters. Leading and trailing spaces are allowed. If the first character cannot be converted to a number, parseFloat returns NaN."

So: parseFloat() pulls a number out of your string, if possible. If the first character is not in its acceptable group, it returns NaN. !isNaN is in our function to check for this result.

You've now got three ways to check if something is a number.

Back to Blog Index...