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);
  console.log(songs[randomIndex]);
};

const playSong = () => {
  var count = 0;
  while (count < 10) {
    randomSong();
    count++;
  }
};

Gareth Dunne

Senior JavaScript Engineer and creator of JSdiaries. Passionate about the latest in web technologies and how it can provide value for my clients.