JavaScript isFinite() Function isFinite() function

This tutorial covers the JavaScript isFinite() function.The isFinite() function returns a boolean (true or false) indicating whether the argument passed to it was a finite number or not (Infinity).

The isFinite() function will always return true, unless it considers an argument to be equal to infinity. As we saw in the MAX_VALUE and MIN_VALUE tutorial, the JavaScript interpreter considers as infinity (the "Infinity" keyword) any number whose value is larger than what it can handle.

For all practical purposes, JavaScript's Infinity keyword and the Number.POSITIVE_INFINITY constant property are equivalent, and can be used interchangeably.

Using the JavaScript isFinite() Function

JavaScript's isFinite() function can be used to ensure that a numerical value is indeed finite, or not equal to Infinity. The script below multiplies the MAX_VALUE property by two, and checks if the result is finite.

var numex = Number.MAX_VALUE * 2;
alert( isFinite(numex) );

We have to remember that JavaScript's notion of infinity is not literal. By definition, since MAX_VALUE is finite, multiplying it by anything else than infinity should not yield an infinite result. However, for the JavaScript interpreter, it does, since the resulting value is larger than anything it can interpret. The isFinite() function returned false (meaning that the result is infinite). JavaScript isFinite() function

Using the isFinite() Function for Data Validation

The isFinite() function can also be used to check for invalid inputs; in a postal web application, the average freight could be calculated by dividing shipping costs by the number of items shipped.

var shippingCost = 50, numberOfItems = 0;

if( !isFinite( shippingCost/numberOfItems ) )
    alert( "At least one item must have been shipped." );

Using the isFinite() function to check data inputs before processing them allows you to avoid invalid inputs. JavaScript isFinite() function as data validator

This is obviously not a recommended error handling method, but it illustrates well realistic scenarios in which the isFinite() function could be helpful, along with the isNaN() function that checks for numerical values.

Test the isFinite() Function

Interactively test the isFinite() function by editing the JavaScript code below and clicking the Test isFinite() function button.

Browser support for JavaScript isFinite() function
Internet Explorer supports the JavaScript isFinite() functionFirefox supports the JavaScript isFinite() functionSafari supports the JavaScript isFinite() functionOpera supports the JavaScript isFinite() function