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 can result in many ways. For Example, dividing any non zero number by zero results in infinity. The Typeof Infinity is a number
console.log(3/0);
console.log(typeof(Infinity));
//**output
//Infinity
//number
Any operations that result in a large number.
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.
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.
console.log(1/Infinity)
//output
//0
The following operations using infinity results in NaN.
console.log(Infinity*0)
console.log(Infinity/Infinity)
console.log(Infinity-Infinity);
//output
//NaN
//NaN
//NaN
Infinity can be either positive or negative.
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.
console.log(Number.POSITIVE_INFINITY);
console.log(Number.NEGATIVE_INFINITY);
//** output **
//Infinity
//-Infinity
Comparing Infinity with numbers works correctly
console.log(Infinity > 1000);
console.log(Infinity == 1000);
console.log(Infinity < 1000);
//**output
//true
//false
//false
console.log(Infinity > -Infinity);
console.log(Infinity == Infinity);
//**output
//true
//true
You can use the Number.isFinite method to verify whether the number is finite.
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.
console.log(Number.isFinite("100"));
//***output **
//false
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