Multiple audio players on blogger

Because the pauseAllButtons() function must happen before the if statement, it becomes less confusing when the first if statement clause is also about pausing the player.

The bad structure that we are trying to avoid is this:

        pauseAllButtons();
        if (player.paused) {
          showPlayButton(button);
          playAudio(audio, button.getAttribute("data-audio"));
        } else {
          pauseAudio(audio);
        }

It’s a bad structure because first we pause the buttons, then the if statement checks if we can play stuff, then the else condition does more pause stuff. That’s a mixed up and confusing way to structure the code.

The good structure that makes the code easier to understand is this:

        pauseAllButtons();
        if (isPlaying(audio)) {
          pauseAudio(audio);
        } else {
          showPlayButton(button);
          playAudio(audio, button.getAttribute("data-audio"));
        }

That code is better structured because the pausing code is all together above the else statement, and the playing code is all together below the else statement.

You can add all of the functions without flipping the statement. The whole purpose of flipping the if statement is to make the code easier to understand, which becomes vitally important when you come back to this code in six months time, or when someone else looks at it too.

1 Like