# Whole Numbers within a Range

I want to understand how each piece of the code works here.

Math.floor(Math.random() * (max - min + 1)) + min

``````function ourRandomRange(ourMin, ourMax){
return Math.floor(Math.random() * (ourMax - ourMin + 1)) + ourMin;
}

ourRandomRange(1, 9)

Below is my understanding (Math.random() * (ourMax  - ourMin +1)) + ourMin;
Please give me a detailed explanation so I understand it correctly.

9 - 1 = 8 (first step)
8 + 1 = 9 (second step)
and Math.random() * 9 = result (3rd step)
And what does the + ourMin; do here?
``````

Math.random gives a random number between 0 and 1.

`max - min + 1` gives the range dimension (for example if the min is 5 and max is 10, the random number could be 5,6,7,8,9,10, so the range dimension is 6)

So if this is the situation, let’s say that in a call, `Math.random()` gives 0.452828472625, this multiplied by 6, gives 2.7169…

Now there is `Math.floor()`, which brings the 2.7… to just 2.

Now there is the `+ min` thing, so 2 + 5 is 7, which is a random number inside the range.

You can also copy the below code where all the steps are separated in a tool like this:
http://pythontutor.com/javascript.html
So that you can see the code in action step by step
(You need a function call for it to work, so add something like `ourRandomRange(2,5)` as last line and play with those calls to see different situations in action

``````function ourRandomRange(ourMin, ourMax){
let randomNumber = Math.random();
let range = ourMax - ourMin + 1;
let randomInRange = range * randomNumber;
let floored = Math.floor(randomInRange);
let result = floored + ourMin;
return result;
}
``````

Well explained. I understand it now. Thank you for your help.