To pick a random element from a JavaScript array, compute a uniformly distributed random index between 0 and array.length - 1 using Math.floor(Math.random() * array.length) for standard UI/simulation randomness, or crypto.getRandomValues() (or Node’s node:crypto randomInt()) when cryptographic unpredictability matters (such as tokens, lottery draws, or security-sensitive sampling)—and always guard against empty arrays so you never return undefined silently when a non-empty item is expected.
1. Standard Random Selection with Math.random()
Use Math.floor(Math.random() * items.length) after validating that items is a non-empty array; because Math.random() returns a float in [0, 1), multiplying by items.length and taking Math.floor() yields every index from 0 to items.length - 1 with equal probability:
// Pick a random element from a non-empty array using Math.random()
function pickRandomItem(items) {
if (!Array.isArray(items) || items.length === 0) {
throw new RangeError("Expected items to be a non-empty array.");
}
try {
const randomIndex = Math.floor(Math.random() * items.length);
return items[randomIndex];
} catch (error) {
throw new Error(`Failed to pick random item: ${error.message}`);
}
}
// Example usage:
try {
const colors = ["red", "green", "blue", "amber"];
const selected = pickRandomItem(colors);
console.log("Selected color:", selected);
} catch (error) {
console.error(`${error.name}: ${error.message}`);
}
- Guard against empty arrays (
items.length === 0):items[Math.floor(Math.random() * 0)]evaluates toitems[0], which isundefined. - Avoid
Math.round(Math.random() * items.length): Rounding can hititems.length(an out-of-bounds index) and slightly skew boundary probabilities.
2. Cryptographically Strong Random Selection (crypto.getRandomValues / node:crypto)
When unpredictability matters—such as fair raffles, shuffle/sampling where predictability is a risk, or security-sensitive choices—avoid Math.random() and use rejection sampling with crypto.getRandomValues() (browser/Web Crypto) or crypto.randomInt(0, items.length) (Node.js):
// Cryptographically unbiased random element picker using Web Crypto rejection sampling
function pickSecureRandomItem(items) {
if (!Array.isArray(items) || items.length === 0) {
throw new RangeError("Expected items to be a non-empty array.");
}
const cryptoObj = globalThis.crypto;
if (!cryptoObj || typeof cryptoObj.getRandomValues !== "function") {
throw new Error("Secure crypto.getRandomValues is unavailable in this environment.");
}
const length = items.length;
const maxUint32 = 0x100000000; // 2^32
const limit = maxUint32 - (maxUint32 % length);
const buffer = new Uint32Array(1);
try {
let value = 0;
do {
cryptoObj.getRandomValues(buffer);
value = buffer[0];
} while (value >= limit);
return items[value % length];
} catch (error) {
throw new Error(`Secure random selection failed: ${error.message}`);
}
}
// Example usage:
try {
const candidates = ["node-a", "node-b", "node-c"];
console.log("Securely selected:", pickSecureRandomItem(candidates));
} catch (error) {
console.error(`${error.name}: ${error.message}`);
}
- Rejection sampling eliminates modulo bias: Discarding values
= limitensures every index has an exact, unbiased chance even when2^32is not divisible byitems.length. - In Node.js (
node:crypto):crypto.randomInt(items.length)provides built-in unbiased integer sampling directly.
3. Picking Without Replacement and Weighted Selection
When you need multiple distinct items (no duplicates) or weighted probabilities rather than uniform single picks, avoid naive repeated pickRandomItem() calls (which can repeat or loop slowly as remaining choices shrink):
// Pick up to `count` distinct elements without mutating the source array
function pickUniqueRandomItems(items, count) {
if (!Array.isArray(items)) {
throw new TypeError("Expected items to be an array.");
}
if (!Number.isInteger(count) || count < 0 || count > items.length) {
throw new RangeError("Expected count to be an integer between 0 and items.length.");
}
const pool = [...items];
const selected = [];
// Partial Fisher-Yates shuffle stops after `count` draws
for (let i = 0; i < count; i += 1) {
const remaining = pool.length - i;
const swapOffset = i + Math.floor(Math.random() * remaining);
const temp = pool[i];
pool[i] = pool[swapOffset];
pool[swapOffset] = temp;
selected.push(pool[i]);
}
return selected;
}
// Example usage:
try {
const deck = ["A", "K", "Q", "J", "10"];
console.log("2 unique picks:", pickUniqueRandomItems(deck, 2));
} catch (error) {
console.error(`${error.name}: ${error.message}`);
}
- Partial Fisher-Yates is
O(count)instead of shuffling the whole array: Stops early once you have drawncountdistinct items. - Clone before shuffling/swapping (
[...items]): Preserves the caller’s original array order intact.
