Is there a simple way to make a random selection from an array in JavaScript or any other programming language?

It’s easy in Python.

>>> import random
>>> random.choice(['red','green','blue'])
'green'

The reason the code you’re looking at is so common is that typically, when you’re talking about a random variable in statistics, it has a range of [0,1). Think of it as a percent, if you’d like. To make this percent suitable for choosing a random element, you multiply it by the range, allowing the new value to be between [0,RANGE). The Math.floor() makes certain that the number is an integer, since decimals don’t make sense when used as indices in an array.

You could easily write a similar function in Javascript using your code, and I’m sure there are plenty of JS utility libraries that include one. Something like

function choose(choices) {
  var index = Math.floor(Math.random() * choices.length);
  return choices[index];
}

Then you can simply write choose(answers) to get a random color.

Leave a Comment