# How to get a random element from an array

JavaScript polyfill, by Bjørn A. Johansen,*Tuesday, April 8th, 2014*

Fetching a random element from an array is pretty straight forward in JavaScript, if you are aware of how to use the build in *Math.random()* method. What this method does, is simply return a random number from and including 0 to but excluding 1, or in more formal terms [0-1[. From this it should be obvious, that if we take this random number and multiply it with the length of the given array, and then floor it, we should get a random index number, so lets try that out;

- var goodTeas = ['Thai tea', 'Indian Chai', 'Hong Kong Milk Tea'],
- randomTea = goodTeas[(function () {
- return Math.floor(Math.random() * goodTeas.length);
- }())];

The *randomTea* variable now contains one of the three teas mentioned in the *goodTeas* array. Of course you can also write a function that gives you a random index number, or extend the *Array.prototype* to have such a method. Extending the prototype of a build in object is not recommended to do, as you could risk conflicting with future native implemented features, but since this is just to make a point, lets look at how to do that anyway;

- Array.prototype.getRandomElement = function() {
- "use strict";
- return this[Math.floor(Math.random() * this.length)];
- };

This would make it very convenient to get a random element from an array, as you can call it directly on any array, just like any other build in *Array* methods.