Explain Codes LogoExplain Codes Logo

Getting a random value from a JavaScript array

javascript
randomness
lodash
prototype
Anton ShumikhinbyAnton Shumikhin·Jan 26, 2025
TLDR

For a random array item, create a fraction with Math.random(), scale it up to the array length, and then round down using Math.floor() to produce a valid index.

const arr = ['apple', 'orange', 'banana']; // Who doesn't like surprises? Let's get a surprise fruit 😃 const randomItem = arr[Math.floor(Math.random() * arr.length)]; console.log(randomItem); // Surprise! It's 'banana'

This formula picks a randomItem from arr:

  • Math.random(): Generates the mystery number (a random fraction).
  • arr.length: Expands the fraction to the size of the array.
  • Math.floor(): Ensures an integer index (no decimals invited to this party).

Expanding the basics: Randomness at scale

Extracting a single random element from an array is cool, but you know what's even cooler? Being able to re-use this magic and get multiple random elements. Let's dip deeper.

1. The slick lodash way

Lodash library offers two handy functions to serve randomness on a platter:

  • _.sample(array): Single random element. Simple as a Sunday morning.
  • _.sampleSize(array, n): N random elements. Because more is merrier!

2. Unleashing the power of prototype

Why not add a custom method, randomElement(), to the Array prototype?

// Because regular arrays are just too mainstream if (!Array.prototype.randomElement) { Array.prototype.randomElement = function() { // smells like... randomness return this[Math.floor(Math.random() * this.length)]; }; } // Let's give it a spin console.log(['apple', 'orange', 'banana'].randomElement()); // 'apple' perhaps?

But remember, with great power, comes great responsibility. Extending native objects like Array can lead to unexpected results and conflicts with other parts of the code.

3. Shaving milliseconds with bitwise operators

If you're competing for microseconds, use bitwise operators like ~~ instead of Math.floor():

// Because who has time for Math.floor in the 21st century, am I right? const randomIndex = arr[~~(Math.random() * arr.length)];

But, be warned, if your array is large enough to scare Godzilla, stick with Math.floor(). Bitwise operations can cause issues with large arrays due to 32-bit integer conversion.

Mastering randomness

Re-running randomness

Running random selection repeatedly? Beware of duplicates. Shuffle your array first with a reliable algorithm like Fisher-Yates, then draw from the start of the shuffled array.

Fully understanding random range

Math.random() is inclusive of 0, exclusive of 1. Hence, multiply by array.length without subtracting 1- that's a game of Russian roulette we're not playing here.

Randomness limitations and caveats

Bitwise operations and array prototype extensions are cool, but remember, every tool has its place. Mind the restrictions and potential conflicts. No tool is a silver bullet!