How to get a random value from a JavaScript array
Feb 07, 2019 · by Tim KamaninRecently 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.
Math.floor(Math.random() * colors.length)
generates a random index for thecolors
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 that 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. Notice, we don't doMath.ceil
to round the number up, because if we get something like0.99 x 5 = 4.95
, it'd be rounded up to5
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;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 ;)