• Post category:JavaScript
  • Reading time:3 mins read

Today, we will show you how to select a random element from an array in JavaScript with example.

Let’s start with an example so you can understand easily. To get a random value, we have to generate a random index number and return it. This is the simple method colors[Math.floor(Math.random() * colors.length)] to get a random value from array.

var colors = [
    'Yellow', 
    'Blue', 
    'Pink', 
    'Red', 
    'Black',
    'White',
    'Green'
];

var color = colors[Math.floor(Math.random() * colors.length)];
console.log(color);

// Output: Pink

How it works:

First, Use the Math.random() function to get index of array that returns a random value between 0 and 1.

var rand = Math.random();
// Output: 0.8517781809554954

Now, using the length property we can get the last index of array that is maximum number.

var totalColors = colors.length;
// Output: 7

Then multiply the random number with the length of the array and round down that result by Math.floor.

var randIndex  = Math.floor(Math.random() * colors.length);
// Output: 2

Finally, using random index we can get a random value from array.

var randColors = colors[Math.floor(Math.random() * colors.length)];
// Output: Pink

If you run this code, you will see the random colour name every time.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!!

Leave a Reply