Get a random Element from an Array using JavaScript

avatar

Borislav Hadzhiev

Thu Oct 28 20212 min read

Get a random Element from an Array #

To get a random element from an array use the Math.floor() and Math.random functions to get a random array index, e.g. arr[Math.floor(Math.random() * arr.length)]. The expression returns a random array index, which you can access to get a random array element.

index.js
const arr = ['one', 'two', 'three', 'four', 'five']; const random = arr[Math.floor(Math.random() * arr.length)]; console.log(random); // ๐Ÿ‘‰๏ธ three

The expression in the square brackets [] evaluates to a random index in the array.

The Math.floor function, rounds a number down if the number has a decimal, otherwise it returns the number as is.

index.js
console.log(Math.floor(4.99)); // ๐Ÿ‘‰๏ธ 4 console.log(Math.floor(4.01)); // ๐Ÿ‘‰๏ธ 4 console.log(Math.floor(4)); // ๐Ÿ‘‰๏ธ 4

The Math.random function returns a random number in the range 0 to less than 1. The function could return 0, but it could never return 1.

index.js
console.log(Math.random()); // ๐Ÿ‘‰๏ธ 0.5434554... console.log(Math.random()); // ๐Ÿ‘‰๏ธ 0.3348588... console.log(Math.random()); // ๐Ÿ‘‰๏ธ 0.8547547... // ๐Ÿ‘‡๏ธ Multiplied by array.length const arr = ['one', 'two', 'three', 'four', 'five']; console.log(Math.random() * arr.length); // ๐Ÿ‘‰๏ธ 1.335... console.log(Math.random() * arr.length); // ๐Ÿ‘‰๏ธ 2.643... console.log(Math.random() * arr.length); // ๐Ÿ‘‰๏ธ 0.393... console.log(Math.random() * arr.length); // ๐Ÿ‘‰๏ธ 4.247...

The max value we could get is, if Math.random() returns 0.9999... and we multiply it by the array's length (5). We would get back a value of 4.995.

index.js
console.log(0.999 * 5); // ๐Ÿ‘‰๏ธ 4.995

However, because indexes are zero-based in JavaScript and the last element in an array has an index of array.length - 1, we use the Math.floor() function to round the number down to the next integer, which is 4 (the last index in the array).

Conversely, the min value we could get is if Math.random() returns 0, we would then multiply that by the array's length and get 0 back.

index.js
console.log(0 * 5); // ๐Ÿ‘‰๏ธ 0

Calling the Math.floor function on 0 would return the number as is and we would access the first element in the array.

The expression returns an index from 0 up to (but not including) array.length. Using this approach, we could never access an index out of bounds.

Here's the complete example.

index.js
const arr = ['one', 'two', 'three', 'four', 'five']; const random = arr[Math.floor(Math.random() * arr.length)]; console.log(random); // ๐Ÿ‘‰๏ธ five

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee