
1. Re: Which of 2 numbers are closest to 0
dln385 Jun 10, 2013 10:31 PM (in response to myDavey)function minMagnitude(a, b) { return Math.abs(a) < Math.abs(b) ? a : b; }
If you're unfamiliar with that syntax, here's an equivalent method:
function minMagnitude(a, b) { if (Math.abs(a) < Math.abs(b)) { return a; } else { return b; } }
And here's another equivalent method:
function minMagnitude(a, b) { var absA; if (a < 0) { absA = a; } else { absA = a; } var absB; if (b < 0) { absB = b; } else { absB = b; } if (absA < absB) { return a; } else { return b; } }
But really, I would stick with the first one.

2. Re: Which of 2 numbers are closest to 0
Peter Kahrel Jun 11, 2013 7:29 AM (in response to dln385)Or this:
function minMagnitude(a, b) { return Math.min (Math.abs(a), Math.abs(b)) }
Peter

3. Re: Which of 2 numbers are closest to 0
dln385 Jun 11, 2013 9:22 AM (in response to Peter Kahrel)I considered that, but it actually doesn't work. minMagnitude(5,2) should return 2, not 2.

4. Re: Which of 2 numbers are closest to 0
myDavey Jun 11, 2013 9:29 AM (in response to dln385)Thanks dln385
This was exactly what I needed.
And yes, Peters code returns the abs number  not the original
dln385,
can you explain your first code?
I understand what your codes are doing (I actually wrote the last code that you wrote, but... its pretty long for no reason)
But what does
? a : b
mean?
Thanks!

5. Re: Which of 2 numbers are closest to 0
dln385 Jun 11, 2013 9:45 AM (in response to myDavey)It's called the ternary conditional operator. (That a bit of a mouthful.)
The syntax looks like this:
condition ? expr1 : expr2
If condition is true, the operator returns the value of expr1; otherwise, it returns the value of expr2.
You can read more about it here: https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Operators/Conditional_Op erator

6. Re: Which of 2 numbers are closest to 0
myDavey Jun 11, 2013 9:48 AM (in response to dln385)Wow, great!
Thanks for the explanation
and Thanks for the site!!!

7. Re: Which of 2 numbers are closest to 0
Peter Kahrel Jun 11, 2013 11:12 AM (in response to myDavey)> And yes, Peter's code returns the abs number  not the original
Indeed! Hadn't spotted that.