Conditionals: if/else and switch
JavaScript branches execution using if/else if/else, the ternary operator, and switch.
const hour = 14;
if (hour < 12) {
console.log("Morning");
} else if (hour < 18) {
console.log("Afternoon");
} else {
console.log("Evening");
}
const label = hour < 12 ? "AM" : "PM"; // ternary operator
switch (hour) {
case 0:
case 12:
console.log("Noon or midnight");
break;
default:
console.log("Some other hour");
}
The ternary operator (condition ? a : b) is a compact expression form of if/else, useful when you need a value rather than a statement — for example, directly inside JSX or a template literal.
switch compares using strict equality internally. Forgetting break causes execution to "fall through" into the next case — sometimes intentional (stacking cases like case 0: and case 12: above), but usually a bug.