How to write a JavaScript function to get the difference between two numbers?

Use Math.abs() inside a JavaScript function to get the difference between two numbers in JavaScript. The Math.abs() method returns the absolute value, ensuring you always get a positive difference regardless of which number is larger.

Syntax

function getDifference(num1, num2) {
    return Math.abs(num1 - num2);
}

Example: Using Math.abs() for Difference

You can try to run the following code to get the difference of numbers:

<html>
   <head>
      <script>
         var num1, num2;
         num1 = 50;
         num2 = 35;
         var difference = function (num1, num2){
            return Math.abs(num1 - num2);
         }
         document.write("Difference = "+difference(num1,num2));
      </script>
   </head>
   <body></body>
</html>
Difference = 15

Multiple Examples

<html>
   <head>
      <script>
         function getDifference(a, b) {
            return Math.abs(a - b);
         }
         
         document.write("50 - 35 = " + getDifference(50, 35) + "<br>");
         document.write("10 - 25 = " + getDifference(10, 25) + "<br>");
         document.write("100 - 100 = " + getDifference(100, 100));
      </script>
   </head>
   <body></body>
</html>
50 - 35 = 15
10 - 25 = 15
100 - 100 = 0

Why Use Math.abs()?

Without Math.abs(), subtracting a larger number from a smaller one gives a negative result. The absolute value ensures you always get the positive difference:

<html>
   <head>
      <script>
         document.write("Without Math.abs(): 10 - 25 = " + (10 - 25) + "<br>");
         document.write("With Math.abs(): 10 - 25 = " + Math.abs(10 - 25));
      </script>
   </head>
   <body></body>
</html>
Without Math.abs(): 10 - 25 = -15
With Math.abs(): 10 - 25 = 15

Conclusion

Use Math.abs(num1 - num2) to calculate the difference between two numbers. This ensures you always get a positive result regardless of the order of the numbers.

Updated on: 2026-03-15T21:56:04+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements