How to Select a Random Element From a JavaScript Array?

You can pick a random element from an array in the following steps:

  1. Generate a random number between 0 and 1 using Math.random();
  2. Multiply the random number with array.length (to get a number between 0 and array.length);
  3. Use Math.floor() on the result to get an index between 0 and array.length - 1;
  4. Use the random index on the array to get an element at random.

For example, let's suppose you have an array of colors like the following from which you wish to pick a color randomly:

const colors = [ 'blue', 'yellow', 'orange', 'red' ];
const randIndex = Math.floor(Math.random() * colors.length);

console.log(colors[randIndex]);

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.