What is the isFinite() method in JavaScript?
The isFinite method is used to check if the value passed to the function is a finite number or not. The isFinite method is available in the window object.
A value is considered a
finitevalue, if the value is not equal toPositive Infinity,Negative Infinity,NaN, andundefined.
Syntax
isFinite(val)
The argument
valwill be be converted toNumberif the passed value is not a type ofNumber.
Return value
The isFinite method returns true if the value passed is a finite value; otherwise it returns false.
Example
console.log("0 :", isFinite(0)); // trueconsole.log("\n10.12 :", isFinite(10.12)); // trueconsole.log("\n-10 : ", isFinite(-10)); // trueconsole.log("\nInfinity :", isFinite(Infinity)); // falseconsole.log("\n-Infinity :", isFinite(-Infinity)); // falseconsole.log("\nNaN :", isFinite(NaN)); // falseconsole.log("\nNaN :", isFinite(undefined)); // falseconsole.log("\n'0' :", isFinite('0'));console.log("\nnull : ", isFinite(null));console.log("\nnull : ", isFinite('test'));
We use the isFinite() method to check if the values are finite.
-
For the numbers
0,10.12,-10isFinitemethod returnstrue. This is because they are all finite numbers. -
For the numbers
+Infinity,-Infinity,NaNandundefined, theisFinitemethod returnsfalse. This is because they are all infinite numbers. -
For the
'0'string, theisFinitemethod will first convert the'0'string to a number. If'0'is converted to a number we will get0, which is a finite value. So,truewill be returned. -
For
null, theisFinitemethod will first convert thenullto a number. Ifnullis converted to a number we will get0, which is a finite value. So,truewill be returned. -
For the
teststring, theisFinitemethod will first convert theteststring to a number. Iftestis converted to a number we will getNaN, which is an infinite value. So,falsewill be returned.