Javascript function to get the difference between two numbers

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

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.


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