In one of my previous posts I’ve shown you how to get a random item from an array in PHP. Well, there is, of course, a way to do this in JavaScript as well. And it’s also very easy. Just declare someting like this:

<script> var allItems = ['A', 'B', 'C', 1, 2, 3, 4, 5]; </script> |

Now you can access the values with their index (which starts at 0 for the first item).

$thirdItem = allItems[2]; |

Next we take a look at a simple way to get a random item from the array by using the `Math.random()`

function for the index of our array. This function returns a random value between 0 and 1. So in order to get a random value within the range of our arrays indices, we must multiply `Math.random()`

with the size of our array.

Math.random()*allItems.length; |

O.K., now we have a number between 0 and 8 (the size of our array in our example). But it’s not an integer. So we’ll have to get an integer value by using the `Math.floor()`

function.

Math.floor(Math.random()*allItems.length); |

Yes, almost done ðŸ˜‰ Now we use our random index to get a random item from this JavaScript array:

<script> var allItems = ['A', 'B', 'C',1, 2, 3, 4, 5]; var randomItem = allItems[Math.floor(Math.random()*allItems.length)]; alert(randomItem); </script> |

That’s it!