Spot the bug - #108: Traffic Light Cycle

Traffic light cycles forever but skips a color, why

const lights = ['red', 'yellow', 'green'];
let index = 0;

function nextLight() {
  const current = lights[index];
  console.log('Now showing:', current);

  switch (current) {
    case 'red':
      index = 1;
      break;
    case 'yellow':
      index = 2;
    case 'green':
      index = 0;
      break;
  }
}

setInterval(nextLight, 1000);

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

Missing “break” in yellow causes it to jump straight to the green case.

ooh a guess on the table, noted. answer drops later today, gonna leave everyone hanging till then :smiling_face_with_sunglasses:

missing break; in yellow case?

Got your entry logged, no confirmations from me though. Answer drops later today.

Spot the Bug answer: The ‘yellow’ case has no break, so it falls through into the ‘green’ case and immediately resets index to 0, skipping green entirely

The fix:
case ‘yellow’: index = 2; break;

Why:
Without a break statement, execution falls through to the next case block, so after setting index to 2 for yellow it immediately overwrites it to 0 from the green case, meaning green never gets displayed on its own turn.


Got it: @kirupa, @Sock

First: @kirupa :trophy:

First-answer leaderboard

  1. @kirupa - 2 (firsts) :trophy:
  2. @emmawalter5 - 1 (first)