views:

95

answers:

4

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.

+4  A: 

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
}
Salil
This is the best solution is any solution using absolute function will provide incorrect results if you wanted to find the difference between a negative and positive number.
Tom Gullen
Why that? Can you give an example where you think Math.abs(a - b) delivers the wrong result?
Frank
@Tom Gullen: `Math.abs(3 - (-5))` will return 8 ;)
Niels van der Rest
Ah sorry, thought the others were comparing abs(num1) - abs(num2) not abs(num1 - num2)
Tom Gullen
I hope there is no difference between `Math.abs(a - b)` and `Math.abs((a) - (b))`
Mithun P
No, those will return the same result. I just added the extra parenthesis for better readability.
Niels van der Rest
Thanks @Niels ...
Mithun P
+6  A: 
var difference = function (a, b) { return Math.abs(a - b) }
mykhal
Alternative (and more used syntax): `function diff(a,b){return Math.abs(a-b);}`Best and simples solution.
Alxandr
.. and then `foo = difference`, to be complete :)
mykhal
Why putting the function in a var ?
Clement Herreman
Clement Herreman: it's a different story. this "varing" is not necessary at all, i just wanted to provide a pure solution (properly define the function in the actual scope)
mykhal
+2  A: 
function difference(n, m){
    return Math.abs(n - m)
}
fmark
+3  A: 

It means you want to return absolute value.

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