JavaScript From Zero · 16 min · 120 XP
Conditionals and guard clauses
Branch with if and the ternary, exit early with guard clauses, and choose ?? over || when 0 is a real value.
if / else if / else choose what runs, checking from the top and taking the first branch that's true. For choosing between two values, the ternary is tidier: const label = inStock ? "In stock" : "Sold out";.
Guard clauses handle the odd cases first and leave the function early, so the main logic isn't buried three ifs deep. Deal with bad input and exit, then write the normal path as if nothing can go wrong, because by then nothing can.
function shippingLabel(order) {
if (!order) return "No order"; // guard
if (order.items.length === 0) return "Empty"; // guard
return order.express ? "Express" : "Standard"; // the real work
}&& and || return one of their operands, not just true/false, so they're often used for defaults: const name = input || "Guest";. But || falls through on any falsy value, including 0 and "". When 0 is a legitimate value (a quantity, a price, a volume), use ??, which only falls through on null or undefined: const qty = input ?? 1;.
Loading your workspace…