Playing with array in javascript using Math.random()

Javascript Jeep🚙💨
Mar 27 · 1 min read

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()

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co

Javascript Jeep🚙💨

Written by

Articles related to javascript

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co