Skip to content
Clean CodeChapter 6 / 57Beginner5 min read

Early Returns & Braces

Remove the nested if pyramid with early return and guard clauses, and learn why every if, else and loop needs braces, with TypeScript examples.

On this page

1. What is this practice?

This practice has three parts:

PartMeaning
Guard clause / early returnSend back a case that cannot continue right away
Braces alwaysEven a one-line body goes inside { }, never a statement on the same line as the condition
Truthy guardWrite if (!user), and use if (user === null) only when the difference between null and undefined is the whole point

2. Why does it matter?

A nested if pyramid is a weight on your mind. At every level the reader has to remember which condition was true. And adding a line to an if without braces is a famous bug.

Nested if and no bracesEarly return and braces
The real logic is hidden 4 levels deepThe real logic is at the bottom of the function, direct
You have to hunt for which if each else belongs toEach guard is complete on its own
A new line added to an if without braces always ranOnly what is inside the braces runs on the condition
One line changed in the diff, and the indentation fools youA clear diff, the edge of the block is visible

The bug without braces looks like this:

ts
if (!user.isAdmin)
  logDenied(user);
  return forbidden();

The indentation says both lines belong to the if. In reality return forbidden() runs for every user, admins too.

3. When to follow it

LevelHow importantWhy
Learning projectVery important, from the first weekThe easiest rule, and it prevents the most bugs
Production codeEnforce with lintESLint curly: ["error", "all"] does this for you
Senior levelFlag nesting in reviewDeep nesting is often a sign that a function does two jobs

4. Bad vs good code

ts
function ship(order: Order | null) {
  if (order) {
    if (order.status === "paid") {
      if (order.items.length > 0) {
        if (order.address) {
          return carrier.book(order);
        } else {
          throw new Error("Missing address");
        }
      } else {
        throw new Error("Empty order");
      }
    } else return null;
  }
  return null;
}
ts
function ship(order: Order | null) {
  if (!order) {
    return null;
  }

  if (order.status !== "paid") {
    return null;
  }

  if (order.items.length === 0) {
    throw new Error(`Order ${order.id} has no items`);
  }

  if (!order.address) {
    throw new Error(`Order ${order.id} has no address`);
  }

  return carrier.book(order);
}
What is the difference?BadGood
Nesting4 levels1 level
Real workIn the middle of the pyramidThe last line, clear
Error placementHunt for which if the else belongs toEach guard has its own error
Braceselse return null without bracesBraces on every block
Adding a new caseThe pyramid gets deeperOne more guard

A guard in React

tsx
export function Profile({ user }: { user: User | null }) {
  if (!user) {
    return <SignInPrompt />;
  }

  return <ProfileCard user={user} />;
}

5. How to apply it

Flattening a nested function
Look at the outermost condition
Invert it: turn if (order) into if (!order)
Return or throw inside the inverted condition
The rest of the code moves out one level
Repeat the same for the next condition
Check braces on every if and else

Make sure with lint:

json
{
  "rules": {
    "curly": ["error", "all"]
  }
}

6. Exceptions and common mistakes

Sometimes nesting shows the domain better, like two equal paths that both do a lot of work (if paid then this, else refund then that). In that case if/else is fine. The goal of early return is to pull guards out, not to get rid of every else.

A truthy guard (if (!count)) is wrong when 0 or an empty string is a valid value. In that case write a clear check: if (count === undefined).

Mistake: A one-line if without braces

Why? When someone adds another line later, it will run outside the condition, whatever the indentation says.

Better: Always use braces and turn on the ESLint curly rule.

Mistake: Condition and statement on the same line

Why? if (!user) return; is easy to miss while scanning, and hard to put a breakpoint on in the debugger.

Better: Put the statement on its own line inside braces.

Mistake: Writing else after a return

Why? If the if already returns, you do not need else, it only adds one level of nesting.

Better: Remove the else and write its code directly below.

Mistake: A truthy guard everywhere when 0 is valid

Why? if (!quantity) treats a zero quantity as missing too.

Better: When a falsy value is valid, write an explicit check for undefined or null.

7. What to learn before and after

Final quick revision

CheckQuestion
GuardsDid the invalid cases leave at the start?
NestingIs the real logic on one level?
BracesDoes every if, else, for and while have braces?
One lineIs any statement on the same line as the condition?
TruthyIs if (!x) catching a valid 0 or empty string?
LintIs the curly rule on?