if (condition) statement1 else statement2 runs the first statement when the condition is truthy, otherwise the optional else part; group several statements in {...}. switch evaluates its expression once and jumps to the first case that is strictly equal (===), then runs until break or return; without break it falls through into the next case. To choose a value, use a ? b : c, || or ?? (Truthiness).
const label = (code) => {
switch (code) { // compared with ===, so "404" never matches 404
case 301:
case 302: return "redirect"; // stacked cases share one body
case 404: return "not found";
default: return code >= 500 ? "server error" : "other";
}
};
const age = 10;
if (age > 18) if (age > 65) console.log("senior"); else console.log("adult"); // no output
console.log(label(503), label(302), label("404"), age >= 18 ? "adult" : "minor");server error redirect other minor
The nested if prints nothing because an else belongs to the nearest if. Use braces, and wrap a case body in { } when it declares variables: all cases share one scope.