Getting a random item from an array

Let’s write a function to return a random element from an array.

We can use Math.random() to generate a number between 0–1(inclusive of 0, but not 1) randomly.


Then multiply the random number with the length of the array.

floor to result to make it whole number .

That’s it we find the random Index.

Let’s explore more …..

Get the random number between specific range


Here we have + min at the end so that it ensures if rand is 0 then we add min so that it results in minimum value provided.

Let’s try to shuffle an array using Math.random()


Leave a comment

Design a site like this with WordPress.com
Get started