Math.floor(Math.random() * (80-50+1)) + 50
How,
Considering, 50
as the min
and 80
as max
of the range.
The Math.random()
results in a floating point number between 0 and 1 (0 inclusive, 1 exclusive).
Multiply it by 31
(the difference of the range + 1) results in a number between 0 and 31 (not including 31).
Adding the minimum value (in here 50) shifts it to a number between min
and 81
(exclusive). So, the number is between min
and min + 31
.
Math.floor()
ensures we round down, so that all integer values from min
to max
are possible. (if we used Math.ceil()
, it skips minimum value, e.g. 50.6)
In step 2, the +1
ensures that the max
(in this example 80) is included after flooring. Without it, the max would be excluded (highest possible result from Math.floor()
would be max - 1
).