JericaWLancaster

random

Filed under
Snippets
on
in
May 17th, 2020.
May 2020.
const random = (min, max) => (
  Math.floor(Math.random() * (max - min)) + min
);

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

// Get a random number out of [10, 11, 12, 13]
random(10, 14);

// Get a random number from 1 to 100 (inclusive)
random(1, 101);

// Get a random number from -10 to 10 (inclusive)
random(-10, 11);

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:

const MAX = 4;

// Get an initial random value.
// Between 0 and 0.999999 (inclusive)
const initialRandom = Math.random();

// Multiply it by our MAX, 4.
// Will be between 0 and 3.999999 (inclusive)
const multiplied = initialRandom * MAX;

// Round it down using Math.floor.
// Will be 0, 1, 2, or 3.
const answer = Math.floor(multiplied);

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:

const MIN = 1;
const MAX = 4;

// Figure out the delta, with subtraction
const DELTA = MAX - MIN;

// Get an initial random value.
// Between 0 and 0.999999 (inclusive)
const initialRandom = Math.random();

// Multiply it by our DELTA, 3.
// Will be between 0 and 2.999999 (inclusive)
const multiplied = initialRandom * DELTA;

// Round it down using Math.floor.
// Will be 0, 1, or 2.
const floored = Math.floor(multiplied);

// Our possible range is 1 short: we want either 1, 2, or 3!
// By adding 1, we shift it up to fit the range perfectly:
const answer = floored + MIN;

Our snippet does all of this work, rolled into a compact expression:

const random = (min, max) => (
  Math.floor(Math.random() * (max - min)) + min
);

Last updated on

May 17th, 2020

# of hits