JavaScript week #1: Randomly pick content from an array

Today I needed to randomly pick content from an array of items in JavaScript. Since I had to look up the syntax, I think it deserves to be noted in my first weekly post documenting my JavaScript learning journey.

Here is an array:

var filters = ["Video", "Image", "Audio", "Slideshow", "Lesson", "Interactive"];

Now I want to randomly generate a number between 1 and 5 to pick an item from the array:

Math.round(Math.random() * (filters.length - 1))

Math.random() is a method that generates a random number between 0-1.

Math.round rounds the number to the nearest whole number, which is needed because the array positions are 0, 1, 2, 3, 4, 5. However, since we get a number between 0 and 1, the rounded value will always be either 0 or 1, which isn't useful. So, we have to multiply it by another number to make it bigger than 1. To make sure the number doesn't go over the maximum number of items in the array, I have used filters.length - 1.

I expected filters.length to return 5 because array indexes start at 0, but the length was actually 6. Turns out that the length returns the actual number of items in an array, but when you refer to the position of an item it'll start from 0. So the first item in array also has the index 0.

Tags: