offline version v3


23 of 264 menu

isFinite function

The isFinite function checks if a parameter is a finite number (that is, not a string, array, etc., and not plus or minus infinity).

How this function works: it will return false if the number is plus or minus infinity (i.e. Infinity) or not a number (i.e. NaN), otherwise it will return true. That is, strings, arrays, etc. will be converted to NaN and will return false accordingly.

However, there are exceptions: an empty string '' returns true, the string '    ' with spaces also returns true, null returns true, for the values true and false it also returns true.

This is because these values are converted to numbers and not to NaN. If you need a really accurate check for a number that does not count a string of spaces, booleans and special values as a number - use the following isNumeric function:

function isNumeric(num) { return !isNaN(parseFloat(num)) && isFinite(num); };

Let's see how it works. The isFinite function converts the parameter to a number and returns true if it is not Infinity, -Infinity, or NaN. Thus, the right side will definitely filter out non-numbers, but leave such values as true, false, null, an empty string '' and a string with spaces, because they are correctly converted to numbers.

To filter out these values, you need the parseFloat function, which for true, false, null, '', '   ' will return NaN. This is how the parseFloat function works: it converts a parameter to a string, i.e. true, false, null become 'true', 'false', 'null' and then reads a number from it, with an empty string and a string with spaces giving NaN. The result of parseFloat is then processed with !isNaN to get true or false instead of NaN. As a result, everything is filtered out, except for strings-numbers and ordinary numbers.

Syntax

isFinite(value);

Example

Now isFinite will output true since the parameter is a number:

let num = 3; console.log(isFinite(num));

The code execution result:

true

Example

Now isFinite will output false since the parameter is not a number:

let num = 'abcde'; console.log(isFinite(num));

The code execution result:

false

Example

Now isFinite will output false since the parameter is infinity:

let num = Infinity; console.log(isFinite(num));

The code execution result:

false

Example

Now isFinite will output false, since 1/0 is essentially Infinity:

let num = 1 / 0; console.log(isFinite(num));

The code execution result:

false

Example

Now isFinite will output true as an empty string that is not a number is an exception:

let num = ''; console.log(isFinite(num));

The code execution result:

true

See also

  • the isNaN function
    that checks for NaN
  • the typeof operator
    that defines a data type
enru