</>YZIF
Back to blog

How to Clean Up Nested If-Else Statements

2026-05-30

The Problem with Nested If-Else

Deeply nested if-else statements are one of the most common sources of code complexity. They make code hard to read, test, and maintain. Here are three practical techniques to clean them up.

1. Early Return (Guard Clauses)

Instead of nesting conditions, return early when a condition is met:

// Before
function getDiscount(age, isMember) {
if (isMember) {
if (age > 65) {
return 0.3;
} else {
return 0.2;
}
} else {
if (age > 65) {
return 0.1;
} else {
return 0;
}
}
}

// After
function getDiscount(age, isMember) {
if (isMember && age > 65) return 0.3;
if (isMember) return 0.2;
if (age > 65) return 0.1;
return 0;
}

2. Switch / Match Expressions

When checking the same variable against multiple values, use switch or pattern matching:

// Before
function getRole(role) {
if (role === "admin") return "Full Access";
else if (role === "editor") return "Edit Access";
else if (role === "viewer") return "Read Only";
else return "No Access";
}

// After
function getRole(role) {
switch (role) {
case "admin": return "Full Access";
case "editor": return "Edit Access";
case "viewer": return "Read Only";
default: return "No Access";
}
}

3. Polymorphism / Strategy Pattern

For complex conditional logic, replace conditionals with polymorphism:

const strategies = {
admin: () => "Full Access",
editor: () => "Edit Access",
viewer: () => "Read Only",
};

function getRole(role) {
return (strategies[role] || (() => "No Access"))();
}

Try It Yourself

Use the If-Else Refactor Tool on YZIF to automatically transform your nested if-else code into cleaner alternatives.