How to get random element from Javascript Array and Display it.

Here we will learn to get random element from Javascript Array and Display it.

We are using javascript for this tutorial. This can be done using jquery also.

This tutorial is divided into 4 steps.

1) Define an array in javascript
2) Math.random() function in javascript
3) array.length in javascript
4) Math.floor() function in javascript

Below is the sample code to define an array, fetch random element from array and display it.


<div id="fruitdiv"></div>
<script type="text/javascript">
var fruitsArr = ["Apple", "Mango", "Banana", "Chickoo", "Tomato"];
var fruit = fruitsArr[Math.floor(Math.random()*fruitsArr.length)];
document.getElementById("fruitdiv").innerHTML = fruit;
</script>

Click on below topics for step by step understanding.
Define an array in javascript
Math.random() function in javascript
array.length in javascript
Math.floor() function in javascript

 

 

Comments are closed.