How to check if a value is a number in JavaScript

By

Learn how to check if a value is a number in JavaScript using the isNaN() function or the typeof operator, which returns number for numeric values.

~~~

The most direct check is typeof value === 'number'. There’s also isNaN(), which answers a slightly different question. Let’s see both, and where each one trips you up.

Checking with typeof

The typeof operator returns the 'number' string if you use it on a number value:

typeof 1 //'number'

const value = 2

typeof value //'number'

So you can do a conditional check like this:

const value = 2
if (typeof value === 'number') {
  //it's a number
}

One surprise here: NaN is a number, as far as typeof is concerned:

typeof NaN //'number'

So a failed calculation, like parseInt('hello'), passes the typeof check while being useless as a number. If the value could come from a calculation, tighten the check:

if (typeof value === 'number' && !Number.isNaN(value)) {
  //it's a usable number
}

Checking with isNaN()

isNaN() is a global function, assigned to the window object in the browser:

const value = 2

isNaN(value) //false

isNaN('test') //true

isNaN({}) //true

isNaN(1.2) //false

If isNaN() returns false, the value can be used as a number.

The isNaN() gotcha

Be careful with this one. isNaN() converts its argument to a number before checking. Some values convert to 0, so they pass the check even though they aren’t numbers at all:

isNaN('') //false
isNaN(null) //false
isNaN('12') //false
isNaN([]) //false

An empty string is not a number, but isNaN('') says false because the conversion produces 0. If you use isNaN() to validate user input, these values slip through. That’s why I consider the typeof check the safer default.

Also, don’t confuse it with Number.isNaN(). That one does no conversion. It only returns true when the value is literally NaN:

Number.isNaN('test') //false
Number.isNaN(NaN) //true

One check that covers everything

Number.isFinite() returns true only for real numbers, excluding NaN and Infinity:

Number.isFinite(2) //true
Number.isFinite('2') //false
Number.isFinite(NaN) //false
Number.isFinite(Infinity) //false

It checks the type and the value in one call, with no conversion. When I need one check to validate a numeric value, this is the one I use.

~~~

Related posts about js: