if...else: Conditional Branching & Guard ClausesConditional statements (if, else if, else) execute different blocks of code based on boolean conditions. Modern JavaScript favors guard clauses and short-circuit evaluation to reduce nested if statements.
flowchart TD
subgraph GuardClause ["Guard Clause Style (Flat & Readable)"]
In1["Function Entry"] --> Guard1{"Invalid Input?"}
Guard1 -- "Yes" --> RetErr["Return Error / Early Exit"]
Guard1 -- "No" --> Guard2{"Unauthorized?"}
Guard2 -- "Yes" --> RetAuth["Return Auth Error"]
Guard2 -- "No" --> ExecCore["Execute Main Business Logic"]
end
| Pattern | Code Example | Advantage |
|---|---|---|
Standard if...else |
if (x) { ... } else { ... } |
Clear binary branching. |
Multi-Branch else if |
if (a) {} else if (b) {} |
Handling mutually exclusive states. |
| Guard Clause | if (!user) return; |
Prevents deep nesting indentation ("Pyramid of Doom"). |
| Ternary Operator | const s = active ? "A" : "B"; |
Concise inline expression assignment. |
// Demonstrating Guard Clauses vs Nested If-Else
// 1. Un-nested Clean Function using Guard Clauses
function processPayment(user, amount) {
// Guard Clause 1: Validate User Existence
if (!user) {
console.error("Error: User session not found.");
return false;
}
// Guard Clause 2: Validate Amount
if (typeof amount !== "number" || amount <= 0) {
console.error("Error: Invalid payment amount.");
return false;
}
// Guard Clause 3: Check Account Balance
if (user.balance < amount) {
console.error("Error: Insufficient funds.");
return false;
}
// Main Happy Path Logic (Flat indentation level!)
user.balance -= amount;
console.log(`Payment of \$${amount} processed! New Balance: \$${user.balance}`);
return true;
}
const account = { balance: 500 };
processPayment(account, 150);
processPayment(account, 1000); // Trigger guard clause
{}: Avoid single-line unbraced if (cond) doSomething(); to prevent logic bugs when adding lines later.cond ? val1 : val2). Avoid nesting ternary operators (a ? b ? c : d : e).Refactor a nested if (a) { if (b) { doSomething(); } } into a single if statement using logical AND (&&).
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.