A random pick looks like a math problem, and teams treat it like one. Someone writes the one-liner, it works in the demo, and then the bug reports arrive. The same quote shows twice in a row and users call the button broken. A pair picker returns the same person twice. A test that touches randomness passes on Monday and flakes on Tuesday. Each report points at Math.random(), and each report is really about the sampling model around it.
The pattern that holds up in review is to decide three things before writing code. One item or several. With replacement or without. Repeats across presses allowed or filtered. The math stays one line in every case. The decisions are what make the behavior defensible, testable, and easy to explain to the next person on the team.
the one-liner, and why floor is the right tool
Math.random() returns a pseudo-random float that is greater than or equal to 0 and less than 1, with roughly uniform distribution over that range. Multiply by the array length and the range becomes 0 up to the length, still exclusive at the top. Math.floor() drops the fraction, which slices the range into one equal bucket per index. For a list of 5, each index owns exactly one fifth of the range, so each item has a 1 in 5 chance per pick.
pick.ts
function pickRandom<T>(items: readonly T[]): T | undefined {
if (items.length === 0) return undefined;
const index = Math.floor(Math.random() * items.length);
return items[index];
}
const lunch = pickRandom(['biryani', 'tacos', 'sushi', 'pizza', 'ramen']);
The empty-array guard earns its place. Without it, an empty list produces index 0 on a list with no index 0, and the function returns undefined by accident instead of by contract. Returning undefined on purpose gives callers one clear case to handle, and the type signature says so.
One edge case is worth naming, because it shows up in code review regularly. Math.round() looks like a friendlier way to land on an integer, and it quietly biases the ends. Rounding maps the top and bottom half-buckets to the first and last index, so those two items get half the probability of the middle ones. Floor keeps every bucket the same width. That equal-width property is the reason floor is the default here, and it is a shorthand worth stating plainly: uniform per index, for the common case of a non-empty list.
objects are arrays with a conversion step
An object has no indexes to pick from, so the first step is converting it to an array. The conversion you choose decides what the pick returns. Object.values() returns the values alone. Object.keys() returns the keys. Object.entries() returns key and value pairs together, which is the right pick when the UI needs to show a label next to the chosen value.
pick-from-object.ts
const prices = { biryani: 14, tacos: 11, sushi: 18, pizza: 13 };
function pickEntry<T>(record: Record<string, T>): [string, T] | undefined {
const entries = Object.entries(record);
if (entries.length === 0) return undefined;
return entries[Math.floor(Math.random() * entries.length)];
}
const chosen = pickEntry(prices);
// chosen is a pair like ['sushi', 18], label and value together.
One property of objects deserves a sentence in the code review. Key order for string keys follows insertion order in modern engines, and integer-like keys sort first in numeric order. A random pick does not care about order, since every entry gets an equal bucket either way. Order matters only when the same list also renders on screen, and then the render and the pick should share one converted array so they agree.
pairs without duplicates
Two independent picks can land on the same item, and for a pair that reads as a bug even when the math is correct. The fix is sampling without replacement: pick from a shrinking pool, so an item leaves the pool once chosen. The compact version shuffles a copy and takes the first two. The shuffle below is Fisher-Yates, which walks the copy from the end and swaps each slot with a random earlier slot, giving every ordering an equal chance.
pick-pair.ts
function pickPair<T>(items: readonly T[]): T[] {
const copy = [...items];
for (let i = copy.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[copy[i], copy[j]] = [copy[j], copy[i]];
}
return copy.slice(0, 2);
}
const pair = pickPair(['biryani', 'tacos', 'sushi', 'pizza', 'ramen', 'salad']);
// Two different items, every run, because the pool shrinks as it goes.
The copy matters. Shuffling the original array mutates state that other components may be rendering, and a picker that reorders the source list creates bugs far from the button that caused them. Shuffle a copy, take what you need, leave the source alone. For a large list where only 2 items are needed, a partial shuffle that stops after 2 swaps does less work, and the full shuffle stays the clearer default for the list sizes most UIs carry (tens of items, not tens of thousands).
the repeat on button press
Sampling with replacement allows the same item twice in a row, and users read that as a broken button. The numbers explain why. With 6 items, the chance that a press repeats the previous pick is 1 in 6, about 17 percent. Press the button 12 times and at least one back-to-back repeat shows up roughly 89 percent of the time. The button works. The experience says otherwise.
The team-level fix is a product decision, stated once and applied everywhere a picker appears. If repeats are filtered, the picker needs memory of the last pick, which in React means state. The filter builds a pool without the previous item and picks from that pool, so the next result differs by construction.
LunchPicker.tsx
import { useState } from 'react';
const LUNCHES = ['biryani', 'tacos', 'sushi', 'pizza', 'ramen', 'salad'];
function LunchPicker() {
const [current, setCurrent] = useState('Press the button.');
function pick() {
const pool = LUNCHES.filter((item) => item !== current);
const next = pool[Math.floor(Math.random() * pool.length)];
setCurrent(next);
}
return (
<div>
<p>{current}</p>
<button type='button' onClick={pick}>Pick lunch</button>
</div>
);
}
Try it: one pick, a pair, and the repeat filter
Try it live on nayemalam.com.
The demo runs the three models side by side. Pick one samples with replacement, with the repeat filter as a toggle so the difference is visible. Pick a pair samples without replacement, so the two slots always differ. The counters make the repeat rate concrete instead of theoretical (1 in 6 per press adds up fast).
when Math.random is the wrong tool
Two situations call for a different source. The first is security. MDN states plainly that Math.random() does not provide cryptographically secure numbers, so tokens, reset codes, and anything an attacker benefits from predicting belong to crypto.getRandomValues() instead. UI picks, games, and shuffle order sit comfortably on Math.random(). The line is whether prediction costs anyone anything.
The second situation is tests. A function that calls Math.random() directly gives a test nothing stable to assert on. Passing the random source in as a parameter keeps production behavior identical and gives tests a fixed sequence to assert against. The default parameter keeps call sites unchanged, so the change costs nothing at the call site and removes a class of flaky tests.
pick-testable.ts
type RandomSource = () => number;
function pickRandom<T>(
items: readonly T[],
random: RandomSource = Math.random,
): T | undefined {
if (items.length === 0) return undefined;
return items[Math.floor(random() * items.length)];
}
// In a test, a fixed source gives a fixed answer:
const fixed = pickRandom(['a', 'b', 'c'], () => 0.99);
// fixed is 'c', every run, because 0.99 * 3 floors to index 2.
The pick itself is one line, and it stays one line. The durable part is the model around it: one item or several, with replacement or without, repeats filtered or allowed, and a random source a test can control. Decide those four in the open, write them down where the next person will find them, and let me know where this flow can improve.
Originally posted on nayemalam.com/blog.
Top comments (0)