Context
In JavaScript, we can generate random numbers using Math.random(). Unfortunately, this function only generates floating-point numbers between 0 and 1.
In practice, it is much more common to need a random integer within a given range. For example, generating a random number between 1 and 10.
Our custom function random() allows use to do just that!
Note: random() includes the first parameter in the range but excludes the second one. For example, random(1, 3) could give us 1 or 2, but never 3. This was done intentionally to match the behavior of Math.random, as well as methods like slice
Usage
// Get a random number between 1 and 100
random(1, 101);
// 5
random(1, 101);
// 36
random(1, 101);
// 100
// Gets a random number between -100 and 99
random(-100, 100);
// 89
random(-100, 100);
// 1
random(-100, 100);
// 99
Explanation
We first create a random float between 0..1 generated by Math.random(). We than apply the max value you specified before rounding it.
If you haven't seen this practice before, it may seem surprising!
Let's say we want to get a random number between 0 and 5. Since Math.random() gives us a random floating number between 0 and 1, we simply multiply the result by 5 and round it down to get our random number:
const max = 5;
// Gets a random value between 0 and 0.999999
const randomFloat = Math.random();
// Multiply it by our max, here 5.
// Gets a float between 0 and 4.999999
const multiplied = randomFloat * max;
// Round it up using Math.floor.
// Get either 0, 1, 2, 3 or 4.
const randomNumber = Math.floor(multiplied);
Now you probably wonder, how do you get a minimum value that is not 0? Or a number between 1 and 5?
The trick here is to get the delta. Here 5 - 1 = 4, so we get a random value between 0 and 3.99999. We can then increase it by our minimum value, to put it in the right range:
const min = 1;
const max = 5;
// Calculate the delta
const delta = max - min;
// Get a random float between 0 and 0.999999
const randomFloat = Math.random();
// Multiply it by our delta, 4
// Will be between 0 and 3.999999
const multiplied = randomFloat * delta;
// Round it up using Math.floor
// This will give us 0, 1, 2 or 3.
const roundedMultiplied = Math.floor(multiplied);
// A random number to which we add the min
// We will finally get 1, 2, 3 or 4.
const final = roundedMultiplied + min;
Conclusion
The final snippet in a compact expression :
const random = (min, max) => {
return Math.floor(Math.random() * (max - min)) + min;
}
Top comments (0)