How to loop through random numbers in JavaScript.

There are kinds of situations when we need to generate random numbers in our web applications. This could be anything from showing a random image to playing a random song using indexes. Ideally, we want to create a loop that outputs random numbers. The random number can then be used for an index value for data;

So, how can we loop through random numbers in JavaScript? Well, this is easily achieved by using JavaScript’s native function, Math.random().

Simply create the loop and output the number each iteration:

const songs = [
  "Blondie - Heart of Glass",
  "Eddie Murphy - Party all the time",
  "The Dubliners - Rocky Road to Dublin",

const randomSong = () => {
  var randomIndex = Math.floor(Math.random() * songs.length);

const playSong = () => {
  var count = 0;
  while (count < 10) {
Proudly published with Gatsby