Eric Range
JavaScript: Is this a number?
Range Eric
Dec 15, 2019
Technical director of Enginsight

Dynamic typing and JavaScript sometimes don’t fit together so well. This is especially important for numbers. A numeric value in a variable is not always declared as a number, although in theory it can only take numeric values.

So how should one check whether it is a number “in the broadest sense” that can be used for further calculations?

In the internet there are numerous suggestions and ideas, which however mostly define a wrong return value for certain value types (objects, arrays, zero, …) and interpret this value as a number, which causes exceptions in the further process.

Here’s my proposal, which intercepts everything that got in my way so far.

function isNumber(number) {
  return !!(number && typeof number !== 'object' && !isNaN(number));
isNumber(1)         => true
isNumber("1")       => true
isNumber("1a")      => false
isNumber("abc")     => false
isNumber(null)      => false
isNumber(undefined) => false
isNumber([])        => false
isNumber({})        => false