Spot the bug - #134: Playlist Generator

Why is my party playlist skipping the final song?

const partyTracks = [
  "Electric Disco Jelly",
  "Neon Flamingo Waltz",
  "Galactic Bagpipe Jam",
  "Midnight Kazoo Solo",
  "Cosmic Polka Fever"
];

function announceSetlist(tracks) {
  const results = [];
  // Announce each track by its slot number
  for (let i = 0; i < tracks.length - 1; i++) {
    const trackNumber = i + 1;
    const title = tracks[i];
    results.push(`Track #${trackNumber}: ${title}`);
  }
  return results;
}

const setlist = announceSetlist(partyTracks);
console.log(`Prepared ${setlist.length} tracks out of ${partyTracks.length}`);
console.log(setlist.join("\n"));

Reply with what is broken and how you would fix it.

Yo it’s the i < tracks.length - 1 in your loop. that - 1 is cutting off the last track. just change it to i < tracks.length to get everything.

Spot the Bug answer: The loop condition i < tracks.length - 1 causes the last element of the array to be skipped.

The fix:
Change the loop condition to i < tracks.length or i <= tracks.length - 1.

Why:
Array indices are 0-based. For an array of length N, valid indices are 0 to N-1. The original condition i < tracks.length - 1 means the loop runs for i from 0 up to tracks.length - 2, effectively missing the element at index tracks.length - 1.

First-answer leaderboard

  1. @kirupa - 6 (firsts) :trophy:
  2. @Apexcodes - 5 (firsts)
  3. @adnanahmed - 2 (firsts)
  4. @emmawalter5 - 2 (firsts)

That’s a classic off-by-one. I’ve seen that exact mistake cause some fun at 3am trying to figure out why the last record wasn’t processing.

Yep, that tracks.length - 1 is a classic. It’s an easy one to miss when you’re deep in the code.

Lol same

That’s how you end up with a playlist of nothing but elevator music.