js
Link to this headingContext
In JavaScript, we can generate random numbers using the Math.random()
function. Unfortunately, this function only generates floating-point numbers between 0 and 1.
In my experience, it's much more common to need a random integer within a certain range. For example, a random number between 10 and 20.
This little helper lets us do that!
Link to this headingUsage
js
Link to this headingExplanation
This function maps the 0..1
range generated by Math.random
to a range you specify. If you haven't seen this practice before, it can be pretty wild looking!
Let's say we're going for a random number between 0 and 4. Because Math.random
gives us a random number between 0 and 1, this is a relatively straightforward problem: we can multiply the result by 4, and round down to get the integer:
js
What if we want a minimum other than 0? What if we want a value between 1 and 4?
The trick is that we need to get the delta. 4 - 1
is 3
, so we'll get a random value between 0 and 2.99999. We can then bump it up by our minimum value, to shift it into the right range:
js
Our snippet does all of this work, rolled into a compact expression:
js