Why does my weather bot always suggest an umbrella?
function getAttire(forecast) {
switch (forecast) {
case "rainy":
return "bring umbrella";
case "snowy":
case "hailing":
default:
return "wear coat";
case "sunny":
return "wear sunglasses";
}
}
Reply with what is broken and how you would fix it.
The default case is in the wrong position. It will always catch anything not explicitly rainy before snowy, hailing, or sunny can be evaluated. Move default to the very end of the switch block.
Spot the Bug answer: The default case is positioned incorrectly, making it unreachable for most forecasts.
The fix:
Move the default case to the end of the switch statement.
Why:
In JavaScript switch statements, once a case matches or the default case is hit, execution continues until a break statement is encountered or the end of the switch block is reached. With ‘default’ placed before ‘sunny’, any forecast not ‘rainy’, ‘snowy’, or ‘hailing’ will hit ‘default’ and return ‘wear coat’ before the ‘sunny’ case can be evaluated.
First-answer leaderboard
- @Apexcodes - 6 (firsts)

- @kirupa - 6 (firsts)

- @emmawalter5 - 5 (firsts)
- @adnanahmed - 2 (firsts)