← Download MyJS

MyJS block

randomItem 1.0.0

Picks one item from an array at random.

Download with this
Exports
randomItem
Works in
Browser and Node.js
Requires
random 1.x
Tags
random
The code of version 1.0.0
/**
 * Picks one item from an array at random.
 * @template T
 * @param {ArrayLike.<T>} arr
 *    The array, or array-like object (such as a string), to pick from.
 * @param {boolean} [useCrypto=false]
 *    If `true`, uses `crypto.getRandomValues()` instead of `Math.random()`, so
 *    the pick can't be predicted.
 * @returns {T}
 *    One of the items in `arr`, each as likely as the others.
 * @throws {RangeError}
 *    If `arr` is empty.
 *
 * @example <caption>Picking a color</caption>
 * randomItem(['red', 'green', 'blue']);
 * // → 'red', 'green' or 'blue'
 *
 * @example <caption>Picking a character from a string</caption>
 * randomItem('aeiou');
 * // → one of the vowels, like 'e'
 */
function randomItem(arr, useCrypto) {
  return arr[random(0, arr.length, { useCrypto, returnInt: true })];
}

Versions

  1. 1.0.0 Oct 23, 2026

    Initial

JSDoc