The Number isFinite() method

By

Learn how the JavaScript Number.isFinite() method checks whether a value is a finite number, returning false for strings, booleans, objects, and arrays.

~~~

Number.isFinite() returns true if the passed value is a finite number. Anything else, booleans, strings, objects, arrays, returns false:

Number.isFinite(1) //true
Number.isFinite(-237) //true
Number.isFinite(0) //true
Number.isFinite(0.2) //true

Number.isFinite('Flavio') //false
Number.isFinite(true) //false
Number.isFinite({}) //false
Number.isFinite([1, 2, 3]) //false

A finite number is any actual number, positive or negative, integer or decimal. The three values that are numbers but not finite are Infinity, -Infinity and NaN:

Number.isFinite(Infinity) //false
Number.isFinite(-Infinity) //false
Number.isFinite(NaN) //false

When would you use it?

The typical case is checking the result of a calculation before you trust it. Dividing by zero in JavaScript does not throw an error. It quietly returns Infinity:

const total = 120
const people = 0

const share = total / people

share //Infinity
Number.isFinite(share) //false

A single Number.isFinite() check catches this, and it catches NaN at the same time, since NaN is not finite either. One test covers both broken outcomes.

It’s also a strict way to validate that a value really is a usable number, not a string or something else that happens to look like one.

How is it different from the global isFinite()?

This is the pitfall. JavaScript also has a global isFinite() function, and it behaves differently. The global version converts its argument to a number first, so numeric strings pass:

isFinite('42') //true
Number.isFinite('42') //false

isFinite(null) //true, null converts to 0
Number.isFinite(null) //false

That coercion causes bugs. isFinite(null) returning true is rarely what you want when you’re validating input.

Number.isFinite() was added in ES2015 exactly to fix this. It performs no conversion at all. If the value is not already of type number, the answer is false, period.

My advice is to always use Number.isFinite() and forget the global one exists. If you receive a string, for example from a form field, convert it explicitly first, then check:

const input = '42'
const value = parseFloat(input)

Number.isFinite(value) //true

This way the conversion is visible in your code, instead of happening silently inside a check.

~~~

Related posts about js: