Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialKelsey Donegan
3,342 PointsWhy does swapping the higher value with the lower value still (mostly) work ?
function getRandomNumber(low, high) { return Math.floor(Math.random() * (high - low + 1)) + low; }
I called with function with the following code
console.log( getRandomNumber(100, 10));
and found that it worked. But then I wondered if it was excluding the values themselves so I narrowed the parameters to
console.log( getRandomNumber(3, 1));
and found that it would only produce the number 2 (unless I just witnessed an insane statistical anomaly.)
It almost makes sense to me, but I'm not fully understanding what's happening here.
1 Answer
mouseandweb
13,758 PointsHi Kelsey,
When you declared the function's parameters, the first argument is 'low' and the second argument is 'high'. So when you call the function you would have the low number first and then the high. For example, you wrote
getRandomNumber(low, high)
which would mean the function call for 100 & 10 and 3 & 1 and should like this:
getRandomNumber(10, 100);
getRandomNumber(1, 3);
What you ran was:
getRandomNumber(100, 10);
getRandomNumber(3, 1);
So your higher number was set in place of the lower number for the random set. OK, so why did you keep getting 2 for getRandomNumber(3, 1) ?
// this is the body of the function
Math.floor(Math.random() * (high - low + 1)) + low;
// now we place in the values as you called them using getRandomNumber(3, 1)
Math.floor(Math.random() * (1 - 3 + 1)) + 3;
// reduce the arithmetic
Math.floor(Math.random() * (-2 + 1)) + 3;
// reduce further
Math.floor(Math.random() * (-1)) + 3;
// reduce Math.random()
// Math.random() returns a random number less than one. So let's say 0.89!
Math.floor(0.89 * (-1)) + 3;
// let's now reduce that random floating point number 0.89 with the -1
Math.floor(-0.89) + 3;
// now Math.floor() will return the lowest whole number.
/// Since this number is negative, the floor of -0.89 is -1.
-1 + 3;
// for the last step, we reduce the -1 and 3 by adding them together and we get
2