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.
views:
95answers:
4
+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
2010-07-01 10:06:12
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
2010-07-01 10:10:44
Why that? Can you give an example where you think Math.abs(a - b) delivers the wrong result?
Frank
2010-07-01 10:18:09
@Tom Gullen: `Math.abs(3 - (-5))` will return 8 ;)
Niels van der Rest
2010-07-01 10:19:19
Ah sorry, thought the others were comparing abs(num1) - abs(num2) not abs(num1 - num2)
Tom Gullen
2010-07-01 10:25:18
I hope there is no difference between `Math.abs(a - b)` and `Math.abs((a) - (b))`
Mithun P
2010-07-01 10:26:06
No, those will return the same result. I just added the extra parenthesis for better readability.
Niels van der Rest
2010-07-01 10:36:16
Thanks @Niels ...
Mithun P
2010-07-01 10:48:59
Alternative (and more used syntax): `function diff(a,b){return Math.abs(a-b);}`Best and simples solution.
Alxandr
2010-07-01 10:10:50
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
2010-07-01 10:31:42
+3
A:
It means you want to return absolute value.
function foo(num1 , num2) {
return Math.abs(num1-num2);
}
Judas Imam
2010-07-01 10:08:53