Retrieve random item from an array in JavaScript

Retrieve random item from an array in JavaScript

Picking random item from an array in JavaScript is a common task and very easy to accomplish.

Here in this post, we will be using JavaScript methods like Math.random() and Math.floor() to write a program to get a random element from the array.

Get Random Item from an Array

To access any item in an array we have to use the index value of it. For example, to access the first element we use array[0] and for the second item we use array[1] and so on.

Here to get random item we have to generate a random number which will be our index value. To do so we will use Math.random() method in JavaScript.

The Math.random() function returns us floating-point (decimal) values between 0 and 1. So to get an number which is greater then 1 we have to multiple it with and integer.


Math.random() * 4 // it will generate random numbers between 0 and 4.

Since the random number is in decimals, we will have to use Math.floor to round it up to the nearest integer that is lower or equal to the random number.

Complete program to get a random item from an array

const array = ['monitor','keyboard','mouse','CPU','GPU'];

function randomItem(array) {
    // generates the random number (i.e index number)
    const randomIndex = Math.floor(Math.random() * array.length);
    // retrieve a random item from the given array
    const item = array[randomIndex];
    return item;
const result = randomItem(array);

In the above program, we have used Math.random()*array.length because we do not want the generated random number be greater than the number of items present in the array.

Related Topics:

Generate Random Number In A Specific Range In JavaScript

3 Ways To Generate Random String/Characters In JavaScript