Loading sound effects into an array I'm loading my game's sound effects into an array to easily pick a random one and play it. Previously, I used a switch statement to select a random sound but it looks less verbose to just pick an array key.
Is it inefficient to use an array to store and play my sound effects? Is there a better way to do this or any improvements I can make to my implementation?
let sounds = [];

function loadSounds() {
  const sources = ['sound1.ogg', 'sound2.ogg', 'sound3.ogg', 'sound4.ogg', 'sound5.ogg', 'sound6.ogg'];
    
  for (let i = 0; i &lt; sources.length; i++) {
      sounds[i] = new Audio(sources[i]);
  }
}

function playRandomSound() {
    const randomNumber = Math.floor(Math.random() * 6);
    
    sounds[randomNumber].play();
}
An array is perfectly fine, it's what I'd prefer as well. But there are some improvements you can make:

When you have an array and you want to create a new array by transforming every item of an old array, it's most appropriate to use Array#map:
// I'd call it `filenames` and `audios`, not `sources` and `sounds`;
// `audios` is plural of Audio and is a bit more precise
const audios = filenames.map(filename =&gt; new Audio(filename));


If your sound files are really numeric-indexed, it would be even easier to just iterate over the numbers 1 to 4, rather than having to list sound1.ogg, sound2.ogg, etc.

Always declare variables with const when possible - only use let when you must reassign the variable name. Using const makes code easier to read, when a reader can determine that the variable name won't ever be reassigned at a glance.

At the moment, if playRandomSound is called multiple times in a row, multiple sounds may be active at once, which may sound very discordant and not be desirable. In such a case, you may wish to save the randomNumber in a persistent outer variable so that you can call .stop() on the prior Audio before .play()ing another. (Or, if you want to have playing sounds overlap, your current approach is just fine)

If your sources array's length changes, you'll also need to change this section: Math.floor(Math.random() * 6); Better to put the array's length there instead of the 6.


const audios = Array.from(
  { length: 6 },
  (_, i) =&gt; new Audio(`sound${i + 1}.ogg`)
);
function playRandomSound() {
    const randomNumber = Math.floor(Math.random() * audios.length);
    sounds[randomNumber].play();
}