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.
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.
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);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.