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:
value
: The value to be tested.
Return Value:
- Returns
true
if the value is a finite number; otherwise, it returnsfalse
.
Key Characteristics:
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.Checks for Finite Values Only: A finite number is a number that is neither
Infinity
,-Infinity
, norNaN
.
Example 1: Basic Usage
In these examples, all three values are finite numbers, so the function returns true
.
Example 2: Non-finite Values
Here, Infinity
, -Infinity
, and NaN
are all non-finite values, resulting in false
.
Example 3: Non-numeric Values
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
.
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) andfalse
forInfinity
,-Infinity
, andNaN
, as well as non-numeric values. - This function is useful for validating numeric inputs and ensuring that calculations are performed with valid numbers.