Explain Codes LogoExplain Codes Logo

Generate random number between two numbers in JavaScript

javascript
functions
promises
callbacks
Anton ShumikhinbyAnton Shumikhin·Sep 15, 2024
TLDR

Get a random floating-point number between min (included) and max (not included):

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

Get a random integer between min and max (both included):

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

Use randomFloat for fractional values and randomInt for integers within your desired interval.

Creating a reusable function

If you're generating random numbers regularly, you might want a reusable function. Here's one that generates a random integer:

function randomIntFromInterval(min, max) { // Who likes rolling dice? return Math.floor(Math.random() * (max - min + 1) + min); } const rndInt = randomIntFromInterval(1, 6); // Dice roll: rndInt is between 1 and 6, inclusive. console.log(`Dice landed on: ${rndInt}`); // Check for snake eyes.

This approach enhances readability and maintainability and reduces the probability of errors when repeating the formula in different parts of your code.

Cryptographically secure random numbers

Security matters. Math.random() is not cryptographically secure. For applications where this is significant, use window.crypto.getRandomValues():

function secureRandomInt(min, max) { const randomBuffer = new Uint32Array(1); window.crypto.getRandomValues(randomBuffer); const randomNumber = randomBuffer[0] / (0xFFFFFFFF + 1); // For when you're picking security keys and not bingo numbers. return Math.floor(randomNumber * (max - min + 1)) + min; }

Note: the Web Cryptography API is your friend when you need quality randomness.

Shortcuts for rounding down

For truncating decimals, here are some shorter ways:

  • Bitwise OR (|) Method: Quick and condensed. Good for 32-bit numbers.

    const rndInt = (Math.random() * (max - min) + min) | 0; // `| 0` floors faster than yo momma's pancakes.
  • Double NOT (~~) Method: Has the same result, but some developers find it more readable.

    const rndInt = ~~(Math.random() * (max - min) + min); // Two negatives apparently make a positive floor. Who knew?

Both have use cases, but be aware they might be less clear to novice JavaScripters.

Handling edge cases

Couple of things to watch out for with random number generation:

  • Negative ranges: Ensure your function also gracefully handles negative ranges.

    randomIntFromInterval(-20, 20); // Works just as well with a negative min value.
  • Large intervals: Remember the safe limit for JS numbers (Number.MAX_SAFE_INTEGER). The randomInt() is not built for an astronomically large range.

Validating randomness

It's crucial to verify that your random numbers are really random:

Efficiency matters

When generating many random values at once, store the random base in a variable to avoid repeated calls:

// What's faster than Math.random()? const randomBase = Math.random(); const rndInt1 = Math.floor(randomBase * (max - min + 1)) + min; const rndInt2 = Math.floor(randomBase * (otherMax - otherMin + 1)) + otherMin;

But remember, doing this might impact the randomness of your result. It's useful in mathematical procedures that depend on the same base value.