How to get random item from JavaScript array


Today I have a requirement in project to retrieve a random value from javascript array. We can do this by using different method.

I have used below code for it.

HTML Button:

Here I have called “ShowArrayItem” function on click event.

Javascript Function:

function ShowArrayItem()
    alert(items[Math.floor(Math.random() * items.length)]);

Here is the javascript static array; you can define it as per your requirement;

var items = Array('sachin', 'sehwag', 'virat', 'yuvraj', 'raina', 'dhoni', 'jadeja');

When you click on button then it will take random value from the javascript items array.

You can also check it online demo from here, random item from JavaScript array

That’s it.