The Infinity
is a global property i.e. it is a variable in a global scope. The Infinity can be either POSITIVE_INFINITY
& NEGATIVE_INFINITY
. We can check whether the number is finite by using the isFinite
method.
Infinity
Infinity
can result in many ways. For Example, dividing any non zero number by zero results in infinity
. The Typeof
Infinity
is a number
1 2 3 4 5 6 7 8 | console.log(3/0); console.log(typeof(Infinity)); //**output //Infinity //number |
Any operations that result in a large number
.
1 2 3 4 5 6 7 8 9 10 | console.log(Math.pow(10, 1000)) console.log(Math.log(0)) console.log(Number.MAX_VALUE + 10**1000); //**output //Infinity //-Infinity //Infinity |
Dividing, Multiplying, and Adding to infinity
is still infinity
.
1 2 3 4 5 6 7 8 9 10 11 12 | console.log(Infinity + 1) console.log(Infinity + Infinity) console.log(Infinity * 3) console.log(Infinity / 3) //**output //Infinity //Infinity //Infinity //Infinity |
But dividing a number by Infinity
is zero.
1 2 3 4 5 6 | console.log(1/Infinity) //output //0 |
The following operations using infinity results in NaN
.
1 2 3 4 5 6 7 8 9 10 | console.log(Infinity*0) console.log(Infinity/Infinity) console.log(Infinity-Infinity); //output //NaN //NaN //NaN |
POSITIVE_INFINITY & NEGATIVE_INFINITY
Infinity can be either positive or negative.
1 2 3 4 5 6 7 8 | console.log(3/0); console.log(-3/0); //**output //Infinity //-Infinity |
POSITIVE_INFINITY
& NEGATIVE_INFINITY
are static properties of Number
object. We can access it using the Number.POSITIVE_INFINITY
and Number.NEGATIVE_INFINITY
.
1 2 3 4 5 6 7 8 | console.log(Number.POSITIVE_INFINITY); console.log(Number.NEGATIVE_INFINITY); //** output ** //Infinity //-Infinity |
Comparisons
Comparing Infinity
with numbers works correctly
1 2 3 4 5 6 7 8 9 10 | console.log(Infinity > 1000); console.log(Infinity == 1000); console.log(Infinity < 1000); //**output //true //false //false |
1 2 3 4 5 6 7 8 9 10 11 | console.log(-Infinity > 1000); console.log(-Infinity == 1000); console.log(-Infinity < 1000); //**output //false //false //true |
1 2 3 4 5 6 7 8 | console.log(Infinity > -Infinity); console.log(Infinity == Infinity); //**output //true //true |
isFinite
You can use the Number.isFinite
method to verify whether the number
is finite.
1 2 3 4 5 6 7 8 | console.log(Number.isFinite(Number.POSITIVE_INFINITY)); console.log(Number.isFinite(100)); //***output ** //false //true |
If you pass a string
to isFinite
, it will result in false
.
1 2 3 4 5 6 | console.log(Number.isFinite("100")); //***output ** //false |
Summary
Here we learned about infinity in JavaScript. The Infinity is very large value, which cannot be represented as 64bit floating point. It can be either POSITIVE_INFINITY
& NEGATIVE_INFINITY
. We can use isFinite
method to check if the given number is infinite.
Read More