Every program makes decisions; writing them clearly keeps logic readable.
if runs a block when its condition is truthy, with optional else if and else branches:
if (score >= 90) grade = "A";
else if (score >= 75) grade = "B";
else grade = "C";The condition doesn't have to be a boolean; it is converted using the truthy/falsy rules. if (items.length) is a common way to say "if there are any items". Be explicit when 0 or "" are valid values, though: if (count) is false when count is 0.
The conditional (ternary) operator cond ? a : b is an expression, so it can be used inside other expressions, return statements and template literals. Keep it to simple cases; nested ternaries quickly become unreadable.
switch compares one value against several cases using strict equality (===). Execution falls through into the next case unless you break (or return), which is occasionally useful for grouping cases but usually a bug:
switch (status) {
case "active":
case "trial":
allow(); break;
default:
deny();
}A pattern that makes conditional code easier to read is the early return (guard clause): handle the invalid or special cases first and return, so the main logic isn't buried inside nested ifs.
For mapping a key to a value, a lookup object (const labels = { a: "Alpha", b: "Beta" }) is often cleaner than a long switch.
Example
function shippingCost(order) {
if (!order.items.length) return 0; // guard clause
if (order.total >= 50) return 0; // free shipping
switch (order.country) {
case "US":
return 5;
case "CA":
case "MX": // grouped cases
return 10;
default:
return 20;
}
}
const order = { items: ["book"], total: 20, country: "CA" };
const cost = shippingCost(order);
console.log(cost === 0 ? "Free shipping" : `Shipping: $${cost}`);
// Shipping: $10Remember
ifconverts its condition with truthy/falsy rules — be explicit when 0 or "" are validcond ? a : bis an expression; keep ternaries shortswitchuses===and falls through withoutbreak
Watch out for
- Forgetting
breakin aswitch, so the next case runs too.