Tell us what’s happening:
Describe your issue in detail here.
Hello freeCodeCampers!
I’m having a hard time understanding this formula and how it works, particularly the +1. Any small hint will be greatly appreciated.
**Your code so far**
function randomRange(myMin, myMax) {
// Only change code below this line
return Math.floor(Math.random() * (myMax - myMin +1)) + myMin;
// Only change code above this line
}
console.log(randomRange(10,5));
**Your browser information:**
User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.61 Safari/537.36
Challenge: Generate Random Whole Numbers within a Range
Math.random() generates numbers from 0 to 1 (not including 1).
Suppose myMin = 3 and myMax = 8, and we want to generate
random number from 3 to 8 (including 8) like 3 4 5 6 7 8
So basically the range length will be 6 or (8 - 3 + 1) or (myMax - myMin + 1) Math.random() * (myMax - myMin + 1) will give you numbers from 0 to 6 (not including 6)
Now we have to shift our range so that it starts from myMin or 3, so we just add myMin. myMin + Math.random() * (myMax - myMin + 1)
And also we remove the fractional part with the help of Math.floor()