Number. isFinite()
Checks whether a value is an ordinary, finite number, not NaN or infinity.
- Returns
trueif the value is a finite number, otherwisefalse.
Example
#console.log(Number.isFinite(42))
console.log(Number.isFinite(5 / 0))
console.log(Number.isFinite(Number('abc')))
console.log(Number.isFinite('42'))
console.log(isFinite('42'))Definition and usage
#The Number.isFinite() function returns true only when the value is of type number and isn’t NaN, Infinity, or -Infinity. It’s the simplest way to make sure the result of a calculation or a text conversion is safe to keep working with.
Infinity shows up more often than you’d expect. Dividing by zero (5 / 0) gives Infinity instead of an error, Math.max() called with no arguments returns -Infinity, and a number written too large in text, like "1e999", turns into Infinity. Number.isFinite() catches all of these along with NaN in a single check.
The function doesn’t convert types: the string "42" isn’t a number, so the result is false. The older, global isFinite() function first converts its argument to a number, so it returns true for "42", and also true for null, because null converts to 0. That’s why new code should prefer the Number version.
Syntax
#Number.isFinite(value)Parameters
#value
any value
The value being checked.
More examples
#function average(scores) {
const result = scores.reduce((sum, score) => sum + score, 0) / scores.length
return Number.isFinite(result) ? result : 0
}
console.log(average([80, 90, 100]))
console.log(average([]))The average of an empty list is 0 / 0, which is NaN. Instead of showing it to the user, the function returns 0.
function parseAmount(text) {
const amount = Number(text.replace(',', '.'))
return Number.isFinite(amount) ? amount : null
}
console.log(parseAmount('12,50'))
console.log(parseAmount('abc'))
console.log(parseAmount('1e999'))Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- After converting text to a number, a single
Number.isFinite(x)check rejects bothNaNand both infinities at once. - Watch out for empty fields:
Number("")gives0, which is a finite number. Check for an empty string separately, before converting it to a number. - Avoid the global
isFinite(), since it silently converts types, e.g.isFinite(null)returnstrue.
Related entries
#Spotted a mistake or missing an example? Write to us.