How to get a random item from an array using JavaScript

By | October 30, 2020

If you want to get a random item from an array using JavaScript, then you can follow the below steps:

Step 1: Let’s say, I have an array of items and I want to show the user’s random item:

var items = [100,200,300,400,500];

Step 2: To get random item from array, I’ll create a function ‘random_item()’:

function random_item(arr)
{
	var item = arr[Math.floor(Math.random() * arr.length)];
	return item;
}

Step 3: I’ll call the random_item() function and pass the array as a parameter in it and print the result using alert box.

$random_item = random_item(items);
alert($random_item);

Here is the complete code:

function random_item(arr)
{
	var item = arr[Math.floor(Math.random() * arr.length)];
	return item;
}

var items = [100,200,300,400,500];
$random_item = random_item(items);
alert($random_item);
Output

Please let me know in the comment box below if you have another way of getting random items from an array.

Leave a Reply

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