JavaScript
# How to get a random value from a JavaScript array

Feb 07, 2019 · Updated: Jul 17, 2021 · by Tim Kamanin

I was recently tasked to create a function that selects a random color from a predefined list of colors.

This is what my array of colors looks like:

```
const colors = ["#FFFFFF", "#F06B4F", "#F2AE52", "#B0CD6D", "#A33120"];
```

And here's the `randomColor`

function I wrote. This function randomly chooses a color from a list:

```
function randomColor(colors) {
return colors[Math.floor(Math.random() * colors.length)];
}
```

Of course, you can use this function to select any random value from an array, not just an array of colors.

We could stop here and call it a day, but let's take a closer look at the `randomColor`

function and see what it does, bit by bit.

`Math.floor(Math.random() * colors.length)`

generates a random index for the`colors`

array;`Math.floor`

function returns the largest integer for a given number;`Math.random`

function returns us a random number in the range of 0 - 1;`Math.random() * colors.length`

, we get a random number between 0 - 1, let's say 0.5 and normalize it, multiplying it by the length of the array (so we don't get the index larger than our array's length);`Math.floor(Math.random() * colors.length)`

, gives us a random integer (array index) by rounding-down our normalized value to the nearest integer. Note that we don't use`Math.ceil`

to round the number up because if we get something like`0.99 x 5 = 4.95`

, it'd be rounded up to`5`

, which gives us an index larger than the length of the array. Thus, we always round down that number:`Math.floor(4.95) = 4`

, i.e. last element of the array;`colors[Math.floor(Math.random() * colors.length)]`

returns us the array element by a random index, just like we wanted.

Below you can see the complete code with an example of how to use it:

```
const colors = ["#FFFFFF", "#F06B4F", "#F2AE52", "#B0CD6D", "#A33120"];
function randomColor(colors) {
return colors[Math.floor(Math.random() * colors.length)];
}
randomColor(colors); // #B0CD6D
```

Hey, if you've found this useful, please share the post to help other folks find it:

- via Twitter: @timonweb
- old school RSS:
- or evergreen email → → →↓ ↓ ↓