"Conditionals: if/else and switch"
Branching logic in JavaScript with if/else chains and the switch statement.
2 min read
Every program needs to make decisions. JavaScript gives you two main tools for that: if/else chains for general conditions, and switch for checking one value against several possibilities.
if, else if, else
const score = 82;
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else if (score >= 70) {
console.log("C");
} else {
console.log("F");
}Each condition is checked in order, top to bottom, and the first one that's truthy runs — the rest are skipped. else catches everything not covered by the conditions above it.
The ternary operator
For a simple two-way choice that produces a value, the ternary operator (condition ? ifTrue : ifFalse) is more compact than a full if/else:
const status = age >= 18 ? "adult" : "minor";It's an expression, not a statement — it evaluates to a value you can assign or return directly. Reach for it only when both branches are short; a ternary with nested ternaries inside it gets hard to read fast.
switch
switch compares one value against several exact matches, which reads more clearly than a long else if chain when you're checking the same variable repeatedly:
const day = "Tue";
switch (day) {
case "Mon":
case "Tue":
case "Wed":
case "Thu":
case "Fri":
console.log("Weekday");
break;
case "Sat":
case "Sun":
console.log("Weekend");
break;
default:
console.log("Not a valid day");
}switch uses strict (===) comparison against each case. Falling through multiple case labels with no code between them (as with "Mon" through "Fri" above) groups them under the same result.
Don't forget break
Without break, execution falls through to the next case regardless of whether it matches — a common source of bugs:
switch (1) {
case 1:
console.log("one");
case 2:
console.log("two"); // this also runs -- no break above it
break;
}
// Logs both "one" and "two"Every case needs its own break (or a return, if the switch is inside a function) unless the fallthrough is intentional.
With branching covered, the next lesson looks at repeating code with JavaScript's loop constructs.