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.
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.