Get a random item from an array in JavaScript

Suppose we have an array in JavaScript. Now we have to get a random item from our array.

An array will allow you to store multiple values in a single variable.

Here I am going to show you the JavaScript code snippet that will get random item value from our JavaScript array.

Below is our JavaScript code that will exactly do this task:

var myArr = [56, 287 , 'media' , 48 , 'pink' , 'green' , 23, 'glorious' , 985 , 88];

var  randArrItem = myArr[Math.floor(Math.random() * myArr.length)];


In the above code, first of all, we have taken our array and store it inside a JavaScript variable. After that, we have taken another variable where we store the random value from our array.

We can get a particular item from an array just by passing the index number just like we can see below:

myArr[3] // Output: media

To take the random value from our JavaScript array, we are passing a random index number of the array within the range instead of sending a fixed index number to get a random item.


Also, read:


In the end, we have passed the random array item variable to our console log to see the result.

Now, if we test our code on the browser, then we will able to see an item from our JavaScript array. Every time we refresh our browser, we will see different array items in a random way.

So we have been successfully able to get a random array item using JavaScript programming language. I hope, this post will beĀ helpful to you.

Leave a Reply

Your email address will not be published. Required fields are marked *