Javascript function to get the difference between two numbers

Solution 1:

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

Solution 2:

Here is a simple function

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

And as a shorter, one-line, single-argument, ternary-using arrow function

function diff (a, b) => a > b ? a - b : b - a

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)
}