Skip to main content Accessibility Feedback

randomNumber.js

Get a random integer with a minimum and maximum value.

Source Code

Example

// Get a random number between 5 and 42
let rand = randomNumber(5, 42);

The helper function

/**
 * Get a random integer with a minimum and maximum value
 * (c) Chris Ferdinandi, MIT License, https://gomakethings.com
 * @param  {Integer} min  The minimum value
 * @param  {Integer} max  The maximum value
 * @return {Integer}      A random number
 */
function randomNumber (min = 0, max = 1000) {
	return Math.floor(Math.random() * (max - min + 1) + min);
}

How it works

The Math.random() method generates a random float (a number with decimals) between 0 and 1.

// returns something like this: 0.37111265461165543
// It will be different every time
let rand = Math.random();

The number the Math.random() method generates is inclusive of 0 (as in, it could sometimes be 0, though I’ve never personally seen that happen), but exclusive of 1 (as in, it will never reach 1).

We’ll create a helper function that accepts a min and max for the random number as arguments.

Then, we’ll subtract the min from the max, and add 1 to it (otherwise the max would never be reached). We’ll multiply the returned value of Math.random() by this new number, and add the min to it. This gives us a random float between our two values.

Finally, we’ll use the Math.floor() method to turn it into an integer, and return the result.

function randomNumber (min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}