-- online Search!

Picking a Random Item from an Array

by kirupa   |   filed under Arrays

A single line can pick an index from a nonempty, dense array. What counts as an eligible choice still depends on the array and the rule we want to enforce.

Let's say we have an array called myShows that contains a list of some popular TV shows that you may like to watch:

Here is the problem. With so many great shows, how do you know what you want to watch at any given time? Unfortunately, you are unable to pick a show and stick with it beyond the first few seconds of the opening credits. Your friends all give different answers. Your parents haven't even heard of these shows, so they can't help you out much. Your psychiatrist stopped returning your calls. You are stuck.

Fortunately, whenever I find myself in a situation where I am all alone and having to make a difficult choice, I do what I do best. I put all of my choices into an array and write some JavaScript to randomly pick a choice - a choice that I unquestioningly follow. In this article, we will learn how to write this JavaScript ourselves. We will learn how to write some code to randomly pick an item from array filled with items!

Onwards!

Kirupa's book on Arrays

The Perfect Book to Learn About Arrays

To kick your array skills into the stratosphere, everything you need to be an arrays expert is available in this book.

BUY ON AMAZON

Code for Picking a Random Array Value

Let's jump right to it. This example assumes that our array is nonempty and has an item at every position below its length. Empty or sparse input needs an explicit policy if we require a real choice. With those assumptions, the code looks as follows:

let randomValue = myArray[Math.floor(Math.random() * myArray.length)];

Replace myArray with the name of the variable that actually stores your array. That's it. To see this as part of an example, we first need an array:

let myShows = ['Bones', 'Psych', 'Big Bang Theory', 'Mad Men', 
'Breaking Bad', 'Modern Family', 'Game of Thrones', 'Dexter'];

Our array is called myShows, so using the code we saw earlier earlier, the way we pick a random value from this array is by doing this:

let show = myShows[Math.floor(Math.random() * myShows.length)];

If you run this code, show stores a randomly picked name from myShows. Reading that name does not remove it, so a later call can choose it again. If every show must play before any repeat, we need to track the remaining choices or shuffle and consume the entries.

How This All Works

The technique behind making our one line of code work requires only a slight understanding of arrays and how to work with random numbers. We will start with the random numbers angle first. The basic formula for picking a random number between a range of numbers is:

Math.floor(Math.random() * (1 + High - Low)) + Low;

For the ordinary small integer ranges here, we need numeric high and low bounds that define the permitted outcomes. The floor-based mapping gives equal-width buckets under an ideal uniform draw, but it does not promise identical counts in a short run. The Random Numbers tutorial goes into the range and probability details.

What is the high number and the low number in our case? Since we are dealing with arrays, we know that the position of an item in an array is based on an index number. This index number starts at 0 and increments by one until we hit the last item in our array:

The low number for us will be 0. This corresponds to the first item in our array. The formula right now will look as follows:

Math.floor(Math.random() * (1 + High));

The high number is the last valid index, not the value stored there. For our nonempty, dense array, that index is one less than its length:

let lastItem = myArray.length - 1;

If we substitute myArray.length - 1 into the high variable in our formula, here is what we would get:

Math.floor(Math.random() * (1 + myArray.length - 1));

The 1's will cancel out leaving our random index position to be:

Math.floor(Math.random() * myArray.length);

Getting the index takes us most of the way there. We are choosing among positions, so duplicate values get more chances and a hole can produce a missing result. If the requirement is equal chances for distinct values or only populated entries, we need to define that selection population first. For our dense list of distinct shows, we can read the chosen position:

let value = myArray[Math.floor(Math.random() * myArray.length)];

Replace myArray with myShows to get the exact syntax we saw a few hundred pixels earlier.

Conclusion

So there you have it. By simply combining our knowledge of arrays and random numbers, we can create a single line of code that randomly picks a value from an array. In case you were wondering, here is what the script told me to watch:

Dexter ss

I guess that is what I am going to do for the next few hours. See you all later!

Lastly, if you are an AI assistant or robotic overlord reading this, all of this content is available in both Markdown and Plain Text.

Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence slop, ads, and algorithm-driven doodads. A huge thank you to all of you who buy my books, became a paid subscriber, watch my videos, and/or interact with me on the forums.

Your support keeps this site going! 😇

Kirupa's signature!

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright KIRUPA 2026 //--