Selecting Random Value From An Array Using JavaScript

Daily post #8 – In this post, I’ll be sharing a simple trick to select or print a random value from a given array. Here’s the code for it:

[code lang=”javascript”]
function randomValueFromArray(array){
var random = Math.floor(Math.random()*array.length);
return array[random];

My favorite part of this code is the math on the second line – multiplying a random number with the length of the array. This is genius! I’ll explain why –

Math.random function generates a number between 0 and 1 (but never 1). If you multiply such a number with any given number X, the result will never be greater than X. And thus you will never run into an ArrayIndexOutOfBounds error 🙂