JS If Else
JavaScript if...else: Conditional Branching and Guard Clauses
The 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.
How if, else if, and else Flow
JavaScript 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.
Guard Clauses vs. Deep Nesting
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 }));
Common Mistakes to Avoid
- Omitting
{}braces on multi-line blocks: Writingif (ready) log(); send();executessend()unconditionally even whenreadyis false. Always wrap blocks in curly braces. - Using
=insideif (...): Writingif (role = "admin")overwritesroleand always runs the branch because"admin"is truthy. - Putting broad conditions first: Testing
score >= 60beforescore >= 90prevents the>= 90branch from ever running. Order thresholds from most specific to least specific.
Frequently Asked Questions
When should I use 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.
Does 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.
What happens if no 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.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.