Clue Mediator

Get a random value from array in JavaScript

📅December 14, 2019

Today, we will show you how to get a random value from array in JavaScript with example.

Get a random value from array in Javascript, How to select a random element from array, Get a random item from an array, Picking a Random Item from an Array, Getting a random value from a JavaScript array, Create a Random Array Picker, Random values in JavaScript.

Checkout more articles on JavaScript

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.

That’s it for today. Happy Coding!