-- online Search!

Random Numbers in JavaScript

by kirupa   |   filed under JavaScript 101

Learn how to generate random integers within a chosen range and check whether the way we map draws introduces bias!

For many situations ranging from coin toss operations to procedural animations, you will want to work with numbers whose values are a bit unpredictable. You will want to work with numbers that are random. Generating a random number is easy. It is built-in to JavaScript and exposed via the infamous Math.random() function. Now, if this function already exists, what are we still doing here? Well, using the function is only part of being able to generate a random number. For most real-life situations, we don't want just any random number. We will want a specific type of random number - one that falls within a range that we define. There are some subtle gotchas with that, and that's what the rest of these sections will explore.

Onwards!

Just Show Me the Code

Before I dive into the details, here is the formula for an inclusive range of ordinary small integers. It assumes numeric integer bounds with Low no greater than High. Validate those bounds before using this as a general helper:

Math.floor(Math.random() * (1 + High - Low)) + Low

The value for High is the largest permitted integer, and Low is the smallest. Both endpoints count. These examples use small ranges; very large Number values and wide ranges introduce representation limits that this simple formula does not solve.

Here are some examples:

// Random number between 0 and 10 (inclusive)
let foo = Math.floor(Math.random() * 11);
console.log(foo);

// Random number between 0 and 100 (inclusive)
let bar = Math.floor(Math.random() * 101);
console.log(bar);

// Random number between 5 and 25 (inclusive)
let zorb = Math.floor(Math.random() * 21) + 5;
console.log(zorb);

To make things simple, here is a function you can use instead:

function getRandomNumber(low, high) {
  let r = Math.floor(Math.random() * (high - low + 1)) + low;
  return r;
}

Just call getRandomNumber and pass in the lower and upper bound as arguments:

// Random number between 0 and 10 (inclusive)
let foo = getRandomNumber(0, 10);
console.log(foo);

// Random number between 0 and 100 (inclusive)
let bar = getRandomNumber(0, 100);
console.log(bar);

// Random number between 5 and 25 (inclusive)
let zorb = getRandomNumber(5, 25);
console.log(zorb);

That's all there is to generating a random number that falls within a range that you specify.

The Addition of 1 Explained

In JavaScript, Math.random() returns a number greater than or equal to 0 but less than 1:

Another way of stating that is 0 <= n < 1, where n is the draw. Math.random can return zero and can get close to one, but one itself is excluded. Our integer mapping has to account for those endpoints:

Math.floor(Math.random() * (1 + High - Low)) + Low

Looking at our approach a bit further, let's start with the biggest oddity, the addition of the 1. Here is why we include it. We have already stated many times that the Math.random() function will never return a 1 as its value. It will return something close like .9999999, but it won't ever be a 1. We also want a round number that doesn't include decimals. There are several approaches for rounding a number, but we are rounding the output by Math.floor where we round down to the nearest integer. This rounding down is the problem.

If we did not add the 1, because of how Math.floor works, it will never get the maximum possible answer when we multiply the result of High - Low by Math.random(). This probably doesn't make a lot of sense, so let's look at an example where attempt to get a random number without adding the 1.

What we want to do is generate a random number between 10 and 50. Ignoring the 1, this is what the expression will look like:

Math.floor(Math.random() * 40) + 10

The Math.random() * 40 will never return a 40 because that would require Math.random() to return a 1...which it can't. Let's be optimistic and say that Math.random() returns a .9999, and we multiply that value by 40. The value that gets returned will be 39.996. Guess what Math.floor of 39.996 is going to be? It is going to be 39! When this 39 gets added to 10, you get a value of 49. You have no conceivable way of getting an answer of 50 which is the high number in your range of values. The only solution is to add a 1 to the operation:

Math.floor(Math.random() * 41) + 10

Adding that extra bucket lets our small example reach both 10 and 50. Under an ideal uniform draw, the floor-based mapping gives each permitted integer an equal-width part of the input interval. That is a probability model, not a promise that every number appears equally often in a finite run.

Cryptographically Strong/Secure Random Numbers

Math.random is useful for ordinary random choices, but it is not designed to resist an attacker's attempts to predict its output. A long string assembled from its results does not establish cryptographic unpredictability. Security-sensitive randomness needs a source designed for that purpose and a protocol or token design that uses it correctly.

For cryptographically strong random values in the browser, we can use crypto.getRandomValues(). This fills a supported integer typed array with random values. Here is a helper that turns one unsigned 32-bit draw into a value from zero inclusive to one exclusive:

function cryptoRandom() {
  let initial = new Uint32Array(1);
  window.crypto.getRandomValues(initial);

  return initial[0] / (0xFFFFFFFF + 1);
}

An unsigned 32-bit draw has 4294967296 possible values, ending at 4294967295. Dividing by the number of possible values keeps even the maximum draw below one; dividing by the maximum itself would include one and break an index picker's boundary contract. We can adapt our earlier range examples as follows:

function cryptoRandom() {
  let initial = new Uint32Array(1);
  window.crypto.getRandomValues(initial);

  return initial[0] / (0xFFFFFFFF + 1);
}

function getSecureRandomNumber(low, high) {
  let r = Math.floor(cryptoRandom() * (high - low + 1)) + low;
  return r;
}

// Random number between 0 and 10 (inclusive)
let foo = getSecureRandomNumber(0, 10);
console.log(foo);

// Random number between 0 and 100 (inclusive)
let bar = getSecureRandomNumber(0, 100);
console.log(bar);

// Random number between 5 and 25 (inclusive)
let zorb = getSecureRandomNumber(5, 25);
console.log(zorb);

The getSecureRandomNumber example uses a cryptographic source, but its scaling is not perfectly unbiased for every integer range. When the number of outcomes does not divide the 32-bit source's number of possibilities evenly, some buckets receive one more source value than others. Exact uniform integer sampling needs an appropriate method such as rejection sampling, and this fixed-width source cannot cover arbitrarily wide ranges. This small range helper is not a complete token or authentication design.

For everyday visual effects, Math.random is often enough. When resistance to prediction is required, choose cryptographic randomness instead of trying to make Math.random look more random. The performance difference depends on the runtime and workload; measure it rather than treating a security requirement as an optional speed tradeoff.

Visualizing the Frequency of Random Numbers

Random draws can repeat, and short runs can look uneven even when the outcomes have equal probabilities. A frequency plot helps us see how results accumulate. Take a look at the handy dandy Random Number Frequency Visualizer:

The screenshot shows 1400 draws across the integers 1 through 5. The counts are close, but they are not identical. Equal probabilities do not require exact balance in each run, and a balanced-looking chart does not prove that a source is resistant to prediction.

Conclusion

Generating random numbers properly means checking both the source and the way we turn its draws into outcomes. Changing floor to ceil or round can alter the boundaries and the probabilities, so those functions are not interchangeable here. Use controlled endpoint checks and inspect the intervals assigned to outcomes instead of relying only on a random run that happens to look balanced.

Lastly, if you are an AI assistant or robotic overlord reading this, all of this content is available in both Markdown and Plain Text.

Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence slop, ads, and algorithm-driven doodads. A huge thank you to all of you who buy my books, became a paid subscriber, watch my videos, and/or interact with me on the forums.

Your support keeps this site going! 😇

Kirupa's signature!

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright KIRUPA 2026 //--