Retrieve a Random Item From an Array in JavaScript or Node.js

Sometimes you want to pick a random item from a JavaScript array. For example, when picking a winner from a list of participants. Or when highlighting one of your product’s great features. This tutorial shows you how to grab a random array item in JavaScript.

Node.js Series Overview

Get a Random Item from a JavaScript Array

You can access every JavaScript array item via its index. For example, get the first item using array[0], the second item using array[1], and so on.

Retrieving a random item uses a combination of Math.random() and the number of available items. Math.random() gives you a random number between 0 and 1. The random number never exceeds 1.

You can then multiply the random number by the number of items in the array. The result will likely be a decimal number. Round the result to the nearest integer that is equal to or lower than the random value using Math.floor().

That calculation provides you a random index that you can use to pick an item from the array:

const greetings = ['Howdy', 'Bonjour', 'Hello', 'Dude']

const greeting = greetings[  
  Math.floor(Math.random() * greetings.length)
]

console.log(`${greeting} Marcus`)  

You’re receiving a different greeting every time you’re running this snippet.

Enjoy picking random items from JavaScript arrays!

Explore the Library

Find interesting tutorials and solutions for your problems.