Basic JavaScript - Generate Random Whole Numbers within a Range - Just Need a Little Explanation

Tell us what’s happening:
I don’t really want to move forward here without fully understanding what’s happening. I know the first ‘+1’ is to avoid the zero index, but why the ‘+ min’ at the end?

Your code so far

``````function randomRange(myMin, myMax) {
Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
// Only change code below this line
return 0;
// Only change code above this line
}
``````

Your browser information:

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36 Edg/106.0.1370.47`

Challenge: Basic JavaScript - Generate Random Whole Numbers within a Range

Link to the challenge:

imagine that Math.random() gave you 0
and imagine that myMin is 10 and myMax is 20

then Math.random() * (myMax - myMin + 1) would evaluate to
0 * (10 + 1)
which is 0
so you need to add myMin (10) to that so that the final random value becomes 10 instead of 0

2 Likes

PERFECT! Thanks a lot.

1 Like