Skip to content

Replace Nested Conditional with Guard Clauses

Flatten deeply nested if/else logic by handling special cases first and returning early, so the main path of a function reads straight down.

6 min readRefactoring

A guard clause is a check at the top of a function that deals with an unusual case and leaves immediately, usually with a return or a throw. Once the special cases are out of the way, the rest of the function only has to describe the normal path. This guide walks through flattening a nested refund calculation into a short list of guard clauses. Interviewers like this one because it is small and mechanical, yet it shows whether you can change structure without changing behaviour and whether you know when a single exit point actually matters.

The problem

A situation where the obvious design starts to hurt.

Ironleaf Studios, a chain of fitness studios, refunds members who cancel a class booking. The rules are simple: only cancelled bookings qualify, bookings paid with class credits get no cash refund, cancelling 24 or more hours ahead returns the full price, cancelling between 2 and 24 hours ahead returns half, and anything later returns nothing.

The code that implements these five rules is four levels deep. Each rule is buried inside the else of the previous one, a temporary refund variable is assigned in five different places, and you have to track every open brace to know which case you are in. Adding a sixth rule, say a staff exemption, means picking the right nesting level and hoping you did not misplace an else.

Before and after

The same code, before and after the change.

Before

type BookingStatus = "active" | "cancelled" | "no_show";

interface Booking {
  status: BookingStatus;
  priceCents: number;
  hoursBeforeStart: number;
  paidWithCredit: boolean;
}

function refundCents(booking: Booking): number {
  let refund: number;
  if (booking.status === "cancelled") {
    if (booking.paidWithCredit) {
      refund = 0;
    } else {
      if (booking.hoursBeforeStart >= 24) {
        refund = booking.priceCents;
      } else {
        if (booking.hoursBeforeStart >= 2) {
          refund = Math.floor(booking.priceCents / 2);
        } else {
          refund = 0;
        }
      }
    }
  } else {
    refund = 0;
  }
  return refund;
}

console.log(refundCents({ status: "cancelled", priceCents: 1800, hoursBeforeStart: 30, paidWithCredit: false })); // 1800
console.log(refundCents({ status: "cancelled", priceCents: 1800, hoursBeforeStart: 5, paidWithCredit: false })); // 900
console.log(refundCents({ status: "no_show", priceCents: 1800, hoursBeforeStart: 0, paidWithCredit: false })); // 0

After

type BookingStatus = "active" | "cancelled" | "no_show";

interface Booking {
  status: BookingStatus;
  priceCents: number;
  hoursBeforeStart: number;
  paidWithCredit: boolean;
}

function refundCents(booking: Booking): number {
  if (booking.status !== "cancelled") return 0;
  if (booking.paidWithCredit) return 0;
  if (booking.hoursBeforeStart >= 24) return booking.priceCents;
  if (booking.hoursBeforeStart >= 2) return Math.floor(booking.priceCents / 2);
  return 0;
}

console.log(refundCents({ status: "cancelled", priceCents: 1800, hoursBeforeStart: 30, paidWithCredit: false })); // 1800
console.log(refundCents({ status: "cancelled", priceCents: 1800, hoursBeforeStart: 5, paidWithCredit: false })); // 900
console.log(refundCents({ status: "no_show", priceCents: 1800, hoursBeforeStart: 0, paidWithCredit: false })); // 0

Why it's worth it

What the change buys you.

Nested conditionals suggest that every branch is equally important. In the refund function that is not true: "not cancelled" and "paid with credit" are exits, not alternatives worth a whole indented block. Turning them into guard clauses tells the reader which cases are special and lets them forget each one as soon as it is handled.

The result is a flat list where each line is one business rule. You can read the function top to bottom and match it to the policy document line by line. The temporary refund variable disappears because each case returns its own value, so there is no longer any risk of a path that forgets to assign it.

Order still matters. The guards are evaluated top to bottom, so the 24-hour check must come before the 2-hour check, exactly as the nested else enforced it before. Flattening keeps that order; it only removes the indentation that hid it.

  • Each business rule sits on its own line at the same indentation level, so the code mirrors the written policy.
  • The temporary result variable goes away, removing the chance of an unassigned or overwritten value.
  • Adding a new special case, such as a staff exemption, is a one-line guard instead of a new nesting level.
  • Reviewers can check the order of rules at a glance, which is where most bugs in this kind of logic hide.

Careful with

  • Guard clauses are for cases that are genuinely exceptional or terminal. If two branches are equally normal, a plain if/else may express that more honestly.
  • Keep the original evaluation order. Swapping the 24-hour and 2-hour guards would silently pay half refunds for early cancellations.
  • If the function must release resources or log on every exit, early returns can skip that code. Use try/finally, a context manager or a wrapper rather than reintroducing nesting.
  • Check for side effects inside conditions. Inverting a condition that calls a function with side effects can change how often it runs.

Step by step

Small, safe steps, with the tests passing after each.

  1. Make sure tests cover every path: not cancelled, paid with credit, 24 or more hours, between 2 and 24 hours, and under 2 hours. Include the boundary values 24 and 2. Run them.

  2. Pick the outermost condition. Invert it (status === "cancelled" becomes status !== "cancelled"), move its else body to the top as a guard that returns 0, and unindent the remaining block. Run the tests.

  3. In the next level, replace refund = 0 for the credit case with return 0, delete its else, and unindent what followed. Run the tests.

  4. Do the same for the 24-hour branch: return the full price directly and remove the else that wrapped the rest. Run the tests.

  5. Turn the 2-hour branch into a guard that returns half the price, and make the final fallback a plain return 0. Run the tests.

  6. Delete the now-unused refund variable and the trailing return refund. Run the tests.

  7. Optionally merge guards that return the same value, such as the first two, if the combined condition still reads as one rule. Run the tests.

Smells it removes

Smells this refactoring helps remove.

Common questions

Short answers to the usual doubts.

Doesn't a function need a single return statement?

That rule comes from languages where every exit had to free memory or close handles by hand. In TypeScript, Python and PHP, cleanup is handled by finally, context managers or destructors, so multiple returns are safe. Clarity of the conditions matters more than counting exits.

Should I merge guards that return the same value?

Only when they express the same idea. Merging status !== "cancelled" and paidWithCredit into one line saves a line but hides two separate rules, so keeping them apart is often clearer. Use Consolidate Conditional Expression when the merged condition has a meaningful name.

When should a guard throw instead of return?

Throw when the input is invalid and the caller made a mistake, such as a negative price. Return when the case is a valid input with a known answer, such as a no-show getting zero refund.

How do I explain this refactoring in an interview?

Say that you are separating special cases from the main path. Show the inversion of the outermost condition, mention that tests covering each branch and the boundaries run after every step, and point out that the evaluation order is preserved.

Does this change performance?

No meaningful change. The same comparisons run in the same order, and each call still does constant work. The gain is in readability and safety of future edits.

Next guide4 of 5 · Techniques: simplifying conditionalsReplace Conditional with Polymorphism: One Class per CaseRead the next one