How to get a random value from a JavaScript array

07 Feb ยท by Tim Kamanin ยท 2 min read

Recently I had a task: create a function that picks a random color from the list of colors.

Here's an array of colors:

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

Now let's write a randomColor function that randomly picks a color from the list:

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

Of course, we can use this function to pick any random value from an array, not only colors.

We could stop here and call it a day, but let's take a look at the randomColor and see what it does, bit by bit.

  1. Math.floor(Math.random() * colors.length) generates a random index for the colors array;
  2. Math.floor function returns the largest integer for a given number;
  3. Math.random function returns us a random number in the range of 0 - 1;
  4. 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 that our array's length);
  5. Math.floor(Math.random() * colors.length), gives us a random integer (array index) by rounding-down our normalized value to the nearest integer. Notice, we don't do 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 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;
  6. colors[Math.floor(Math.random() * colors.length)] returns us an element of the array at the random index, just like we wanted.

The final code looks like:

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

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

randomColor(colors); // #B0CD6D ;)

Want to get more ๐Ÿ”ฅ tips like this one?

Subscribe to get notified about new dev tutorials