# Tutorial :Javascript function to get the difference between two numbers ### Question:

I want a Simple Javascript function to get the difference between two numbers in such a way that `foo(2, 3)` and `foo(3,2`) will return the same difference 1.

### Solution:1

``var difference = function (a, b) { return Math.abs(a - b); }  ``

### Solution:2

Using ternery

``function foo(num1, num2){    return (num1 > num2)? num1-num2 : num2-num1  }  ``

Or

``function foo(num1, num2){    if num1 > num2      return num1-num2    else      return num2-num1  }  ``

### Solution:3

Seems odd to define a whole new function just to not have to put a minus sign instead of a comma when you call it:

``Math.abs(a - b);  ``

vs

``difference(a, b);  ``

(with difference calling another function you defined to call that returns the output of the first code example). I'd just use the built in abs method on the Math object.

### Solution:4

It means you want to return absolute value.

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

### Solution:5

``function difference(n, m){      return Math.abs(n - m)  }  ``

### Solution:6

In `TypeScript`, if anyone interested:

``public getDiff(value: number, oldValue: number) {      return value > oldValue ? value - oldValue : oldValue - value;  }  ``

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »