JavaScript Number.isFinite(value) function


The Number.isFinite(value) function in JavaScript is a static method that determines whether the passed value is a finite number. This function is part of the Number object and provides a more robust check compared to the global isFinite() function, as it does not coerce the argument to a number type.

Syntax:

Number.isFinite(value)
  • value: The value to be tested.

Return Value:

  • Returns true if the value is a finite number; otherwise, it returns false.

Key Characteristics:

  1. No Type Coercion: Unlike the global isFinite() function, Number.isFinite() does not convert non-numeric values to numbers before checking if they are finite. This makes it more reliable when validating the type of a value.

  2. Checks for Finite Values Only: A finite number is a number that is neither Infinity, -Infinity, nor NaN.

Example 1: Basic Usage

console.log(Number.isFinite(123)); // true console.log(Number.isFinite(-123.45)); // true console.log(Number.isFinite(0)); // true

In these examples, all three values are finite numbers, so the function returns true.

Example 2: Non-finite Values

console.log(Number.isFinite(Infinity)); // false console.log(Number.isFinite(-Infinity)); // false console.log(Number.isFinite(NaN)); // false

Here, Infinity, -Infinity, and NaN are all non-finite values, resulting in false.

Example 3: Non-numeric Values

console.log(Number.isFinite("123")); // false console.log(Number.isFinite(true)); // false console.log(Number.isFinite(null)); // false console.log(Number.isFinite(undefined)); // false

In these cases, non-numeric values such as strings, booleans, and null do not count as finite numbers, so the function returns false.

Example 4: Checking NaN

The behavior of Number.isFinite() with NaN is noteworthy since it will return false.

console.log(Number.isFinite(NaN)); // false

Summary:

  • The Number.isFinite(value) function checks if a value is a finite number without converting it to a number type.
  • It returns true for finite numbers (including negative and positive values) and false for Infinity, -Infinity, and NaN, as well as non-numeric values.
  • This function is useful for validating numeric inputs and ensuring that calculations are performed with valid numbers.