Skip to content
jshacks.dev
Fundamentals

Get a random item from an array

Pick a random item from an array with Math.random, and see why rounding the index instead of flooring it makes the middle item twice as likely. Node.js 18.

2 min read
Summarize in AI

items[Math.floor(Math.random() * items.length)] is the standard random pick, and the variant with Math.round looks the same and is wrong. The counts below come from Node.js 24.

JavaScript
const pick = (items, random = Math.random) => items[Math.floor(random() * items.length)];

const colors = ['red', 'green', 'blue'];
console.log(pick(colors, () => 0), pick(colors, () => 0.5), pick(colors, () => 0.9999));
console.log(pick([], () => 0.3));

const roundBased = (items, random) => items[Math.round(random() * (items.length - 1))];
const counts = { red: 0, green: 0, blue: 0 };
for (let i = 0; i < 3000; i++) counts[roundBased(colors, () => i / 3000)]++;
console.log(counts);
Text
red green blue
undefined
{ red: 750, green: 1500, blue: 750 }

Math.random() returns a number from 0 up to but not including 1, so multiplying by the length and flooring gives each index the same share. The function in the example takes the generator as an argument, so the output uses fixed values: 0 picks the first color, 0.5 the second and 0.9999 the last. Rounding spreads the range unevenly, because the first and last indexes each get only half a slot. With 3,000 evenly spaced inputs, roundBased picked green 1,500 times and the other two 750 each. An empty array gives undefined, as the second line shows. The generator is described in the specification for Math.random.

Math.random() is not secure, so do not use it to pick a token, a password or a lottery winner. Use randomInt from node:crypto for that. Taking the generator as a parameter also makes a function testable, since a test can pass a fixed value and get a fixed answer.

Taggednode 24
Share

More snippets

Fundamentals

Sort dates in an array

Sort an array of Date objects by subtracting them, and see why the default sort orders dates by weekday name. Works in every Node.js release.

1 min read
Fundamentals

Sort by multiple keys

Sort records by several keys in one comparator with toSorted, falling through to the next key when the first ties. Needs Node.js 20, stable since ES2019.

1 min read
Fundamentals

Create a URL with search params

Build a URL with query parameters using URL and searchParams, and see how spaces and ampersands are encoded, plus how to resolve a relative path. Node.js 18.

2 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.