PUBLISHED ON: MARCH 3, 2023
JavaScript Program to Get Random Item From an Array
In JavaScript, an array is a collection of values stored in a single variable. Obtaining a random item from an array is a typical operation that is required in many programming contexts. For instance, if you have a list of names, and you want to display a random name each time a visitor visits your website, you will need to acquire a random item from the list.
There are different ways to do this work, however in this post, we will investigate some efficient and effective approaches to get a random item from an array using JavaScript.
We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and learn more from here.
Program to Get Random Item From an Array
In the program given below, a random item from an array is accessed.
- A random number between 0 to length of the array is generated using the
Math.random()
method.
- The
Math.floor()
returns the nearest integer value generated by Math.random()
.
- This random index is generated and then the element in that particular index is returned.
// JavaScript Program to get a random item from an array
function getRandomItem(arr) {
// get random index value
const randomIndex = Math.floor(Math.random() * arr.length);
// get random item
const item = arr[randomIndex];
return item;
}
const array = [1, 'hello','world' ,22, 5, 8];
const result = getRandomItem(array);
console.log(result);
5
Conclusion
Getting a random item from an array is a popular operation in JavaScript programming, and there are a number of ways to accomplish this. This article explores three distinct JavaScript ways for selecting a random item from an array. This article should have helped you learn how to retrieve a random item from an array in JavaScript; you may now apply this information to your own projects.