Getting a random value from a JavaScript array.

This is a short tutorial on how to get a random value from a JavaScript array. To do this, we will have to generate a random index number that represents an element in the array.

Let’s jump straight into an example:

In the JavaScript code above, we created a custom function called getRandomArrayElement(). This function takes in an array as a parameter and returns a random element.

Inside this function:

  1. We set the minimum number to 0. This is because arrays indexes start at 0.
  2. Using the length property, we worked out what the last index will be. This is our maximum number.
  3. Once we figured out the minimum and maximum value, then generated a random integer value between the minimum and maximum values. To do this, we used theĀ Math.floor() method andĀ Math.random() methods.
  4. Finally, we returned the array value that corresponds to the integer that we generated.

For the sake of this example, I created a JavaScript array containing different types of animals. If you run the code, you will see that a random animal name is logged to the console each time.

And that’s it!

Facebook Comments