4 Example(s) of Javascript Infinity


Description :

Infinity is of two types - Positive and Negative, So if calculation go beyond the upper of lower limit it shows infinity. In our example, We are going to show negative and positive infinity both in span.


Javascript Infinity Example - 1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<p>2.797693439493157E+10308 will show the positive infinity and  -1.7976931348623157E+10308 will show the negetive infinity .</p>
<p>Click the button to see for yourself.</p>
<button onclick="infinity()">Click it</button>
<p id="sample"></p>
<script>
function infinity() {    
    document.getElementById("sample").innerHTML = 
 2.797693439493157E+10308 + "<br>" +  -1.7976931348623157E+10308;
}
</script>
</body>
</html>

Output

Description :

In this example, we will show both the infinity values using Number.POSITIVE_INFINITY and Number.NEGATIVE_INFINITY, Which will print "infinity" and "-infinity" in the p tag.


Javascript Infinity Example - 2
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<p>Click the button to display positive and negative infinity.</p>
<button onclick="infinity()">Click it</button>
<p id="sample"></p>
<script>
function infinity() {
document.getElementById("sample").innerHTML = Number.POSITIVE_INFINITY +"<br/>" + Number.NEGATIVE_INFINITY;
}
</script>
</body>
</html>

Output

Description :

I think, you must have heard about divide by zero to get infinity value, so in this example we are going to divide 100 by 0 and which will result in infinity. See the code


Javascript Infinity Example - 3
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
     
</head>
<body>
<p>Click the button to display divede by zero infinity.</p>
<button onclick="infinity()">Click it</button>
<p id="sample"></p>
<script>
function infinity() {
    var y = 100;
    document.getElementById("sample").innerHTML = y/0;
}
</script>
</body>
</html>

Output

Description :

In this example, we are going to generate the infinity value by multiplying number.maxvalue with 2. See the code snippet:


Javascript Infinity Example - 4
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<p>Click the button to create a positive infinity.</p>
<button onclick="positiveInfinity()">Click it</button>
<p id="sample"></p>
<script>
function positiveInfinity() {
    var number = (Number.MAX_VALUE) * 2;
    document.getElementById("sample").innerHTML = number;
}
</script>

</body>
</html>

Output