Skip to content

Randomising in JavaScript

Math.random() returns a pseudo-random number that is at least 0 and less than 1. Everything else, such as a dice roll, a random array item or a shuffled list, is built by scaling that number and rounding it. The examples on this page give a different result on every run, so the output blocks show the shape of the output, not values you will see.

console.log(Math.random());
console.log(Math.random());

One run printed:

0.5390760719080314
0.3918527687176476

The result can be 0 but never reaches 1. The numbers come from an algorithm seeded by the engine, so they look random but are predictable to anyone who knows the internal state, and there is no way to set the seed yourself.

Multiplying by the number of possible values spreads the result over that many units, Math.floor turns it into a whole number counted from 0, and adding the minimum moves the range into place:

function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 6));
console.log(randomInt(1, 6));
console.log(randomInt(100, 200));

One run printed:

4
1
110

Both ends are included, so randomInt(1, 6) can return 1, 2, 3, 4, 5 or 6. The + 1 is what makes max reachable, because there are max - min + 1 whole numbers from min to max. Use Math.floor rather than Math.round here, because rounding gives the two end values only half the chance of the others.

An array’s indexes run from 0 to length - 1, so the minimum is 0 and the formula reduces to a single line:

const snacks = ['apple', 'banana', 'crisps', 'flapjack', 'yoghurt'];
const pick = snacks[Math.floor(Math.random() * snacks.length)];
console.log(pick);

One run printed:

crisps

The same line picks a random CSS class, a random greeting or a random colour from any array.

The Fisher–Yates shuffle walks backwards through the array and swaps each item with a randomly chosen one at or before it, which gives every order an equal chance:

function shuffle(items) {
const result = [...items];
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}
console.log(shuffle(['red', 'amber', 'green', 'blue', 'violet']));

One run printed:

[ 'violet', 'blue', 'red', 'amber', 'green' ]

The function copies the array first, so the original keeps its order. A shortcut sometimes seen online, items.sort(() => Math.random() - 0.5), is biased, because sorting algorithms do not expect a comparison to change its answer, so some orders come up far more often than others.

Math.random() must not be used for anything an attacker could benefit from guessing, such as passwords, tokens or session IDs. The Web Crypto API, available as crypto in browsers and in Node.js, draws on the operating system’s secure source instead:

console.log(crypto.randomUUID());
const bytes = new Uint32Array(3);
crypto.getRandomValues(bytes);
console.log(bytes);

One run printed:

d675a727-f81d-4626-ae15-0f1d02fe61c1
Uint32Array(3) [ 3850111757, 3284165550, 725103110 ]

randomUUID() returns a new version 4 UUID each time, and getRandomValues() fills a typed array with random whole numbers. In browsers, crypto.randomUUID() is available only on secure pages, which means those served over HTTPS or from localhost.

Steve Griffith covers this topic in his video Randomizing in JavaScript.