DEV Community

JulianneHuynh
JulianneHuynh

Posted on

Randomizing Array Elements

If the Math.random() function didn't work for you it's okay. As a newbie to coding, it took me over a day for it to work it's magic. There are a number of ways to create a random return but I found this to be the cleanest way that made the most sense. The syntax behind this code may seem a little dauting but once you break it down it's much simpler than you think.

Image description

Here we have an array of dog names. In order to randomize the dogs' names the function was called on the array, dogs. The function Math.floor(), essentially rounds down an integer, but since these are names it won't return just a quarter of the name. To generate a random return of an element of the array Math.random() is multiplied to the length of the array, array.length. The length covers the entirety of the array of all the elements.

Top comments (0)