Open In App

How to check if a number evaluates to Infinity using JavaScript ?

Last Updated : 09 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The task is to check whether the number evaluates to infinity or not with the help of JavaScript. Here are a few techniques discussed. 

Approach 1: Checking if the number is equal to the Number.POSITIVE_INFINITY or Number.NEGATIVE_INFINITY .

Example: This example uses the approach discussed above. 

html




<body style="text-align:center;">
      id="body">
    <h1 style="color:green;" 
        id="h1">
        GeeksForGeeks
    </h1>
    <h3>
        Check if number is Infinity?
    </h3>
    <p id="GFG_UP" 
       style="font-size: 15px;
            font-weight: bold;">
    </p>
    <button onclick="GFG_Fun()">
        click here
    </button>
    <p id="GFG_DOWN" 
       style="color:green;
            font-size: 20px;
            font-weight: bold;">
    </p>
    <script>
        var up=document.getElementById('GFG_UP');
        var down=document.getElementById('GFG_DOWN');
        var n=1/0;
        up.innerHTML="Click on the button to check if"+
            " Number evaluates to Infinity.<br> Number = 1/0";
  
        function GFG_Fun() {
            if(n==Number.POSITIVE_INFINITY||n==Number.NEGATIVE_INFINITY) {
                down.innerHTML="Infinity";
            } else {
                down.innerHTML="Not Infinity";
            }
        }
    </script>
</body>


Output:

 

Approach 2: Using Number.isFinite() method to check if the number is finite or not.

Example: This example uses the approach discussed above. 

html




<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
    <h3>
        Check if number is Infinity?
    </h3>
    <p id="GFG_UP" style="font-size: 15px;
            font-weight: bold;">
    </p>
    <button onclick="GFG_Fun()">
        click here
    </button>
    <p id="GFG_DOWN" 
       style="color:green;
              font-size: 20px;
              font-weight: bold;">
    </p>
    <script>
        var up=document.getElementById('GFG_UP');
        var down=document.getElementById('GFG_DOWN');
        var n=1/4;
        up.innerHTML="Click on the button to check if"+
            " Number evaluates to Infinity.<br> Number = 1/4";
  
        function GFG_Fun() {
            if(!Number.isFinite(n)) {
                down.innerHTML="Infinity";
            } else {
                down.innerHTML="Not Infinity";
            }
        }
    </script>
</body>


Output:

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads