Simple Problem just need help clarify

I completed the problem just confuse on what + 1 inside the range does and also the extra + myMin at the end.

  **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
}
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36.

Challenge: Generate Random Whole Numbers within a Range

Link to the challenge:

Hello there,

To start with the + myMin:

  • Math.random() returns a number from 0 -> 1 (not including 1)
  • So, if Math.random() returned 0, then the function would return 0, even if you set your myMin to 10 (without the + myMin)
  • With the + myMin, the minimum value returned will at least always be myMin

The +1 is to counteract the fact that Math.floor is going to decrease the answer. So, take a simple case without it:
randomRange(0, 5)

  • myMax - myMin === 5
  • Pretend Math.random() returned 0.99999
  • Math.floor(5*0.9999999) === 4

So, the max you could get (without the +1) is myMax - 1, which is not what you want. Because you want to include the max in the range of possible values.

Hope this clarifies

1 Like