if...else: Conditional Branching and Guard ClausesThe JavaScript if...else statement runs different blocks of code depending on whether a condition evaluates to truthy or falsy. Adding else if lets you test several mutually exclusive cases in order from top to bottom.
if, else if, and else FlowJavaScript checks conditions sequentially and executes only the first branch whose condition is truthy. Once a branch matches, all remaining else if and else blocks are skipped completely.
When a condition handles a simple single-line value assignment, a ternary expression (const label = isPaid ? "Paid" : "Pending";) is cleaner than a four-line if...else block.
Deeply nested if blocks push code far to the right and obscure the happy path. Returning early with guard clauses handles invalid cases at the top of a function and keeps main logic flat.
function getShippingQuote(order) {
if (!order) {
return "Order missing";
}
if (order.items.length === 0) {
return "Cart is empty";
}
if (order.total >= 50) {
return "Free shipping";
}
return "Standard shipping: $6.00";
}
console.log(getShippingQuote({ items: ["Book"], total: 65 }));
console.log(getShippingQuote({ items: ["Pen"], total: 12 }));
{} braces on multi-line blocks: Writing if (ready) log(); send(); executes send() unconditionally even when ready is false. Always wrap blocks in curly braces.= inside if (...): Writing if (role = "admin") overwrites role and always runs the branch because "admin" is truthy.score >= 60 before score >= 90 prevents the >= 90 branch from ever running. Order thresholds from most specific to least specific.if...else instead of a ternary ? :?Use if...else whenever branches run statements, throw errors, or exceed one short line. Reserve ternaries for simple value selection inside assignments or JSX.
else if require curly braces?Keep curly braces around every if, else if, and else block. Consistent braces prevent accidental bugs when adding a second line later.
if or else if matches and there is no else?JavaScript skips all branches and continues running the next statement immediately after the conditional block.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.