The floor of a number is the nearest integer less than the number. We are essentially truncating the whole number portion (removing the decimal fraction).
3.14 => a JS float
3 => the floor of 3.14
Recall that Math.random() generates only a decimal fraction (a float) less than 1, but possibly equal to zero, or anything in between.
Eg.
0.8503869061523449
The above is a typical random number returned from the Math.random() method. As it stands, it is less than 1 so if we floor it we end up with zero, no matter what it is. That’s all that is left over after truncation. 0.
If we multiply the float by a number greater than one we will have at least one digit to the left of the decimal point.
2 * 0.8503869061523449 == 1.7007738123046898
Well, that is unless the number is less than 0.5. This will still be less than 1 when multiplied by 2. The net effect when we floor the result is either 0 or 1.
y = Math.floor(Math.random() * 2)
// { y | y is Integer and y is a member of [0, 1] }
It’s possible that multiplying by any number will still result in a value less than 1. That makes a floor value of zero always possible. We can therefore take measures to offset the floor value by some amount, 1 or more.
Eg.
r = Math.floor(Math.random() * 6) + 1
Above the floor value will be 0..5 and the offset we’ve given is +1. That gives us a typical roll of the die. One to six, inclusive.
Take it slow, and question everything, even this same topic. Spend some time in the console playing with this. How could we give the same functionality to negative numbers?
You mean, -6? The floor will always be less than the number we start with, unless it is already integer. Be careful not to confuse this with rounding. That works on a different principle.