Get a random element from a JavaScript array

Table of Contents

To get a random element from an array, you can use a couple of Math functions to generate a random index and retrieve a value.

function random(items) {
	return items[Math.floor(Math.random() * items.length)]

Math.random() generates a random float between 0 and 1. The generated float is always less than 1, so when we multiply it by the length of the array, it's always going to be less than items.length.

Since the result of this operation is a floating-point number and arrays are integer-based, we can use Math.floor() to round that number down.

This approach guarantees that the generated index is always in the range 0..items.length and will never produce an invalid index.

Enjoyed this post or found it useful? Please consider sharing it on Twitter.