Emmanuel Akinfulubi

JavaScriptBasic

Use guard clauses instead of nested ifs in JavaScript

Beginner · 4 min read

Validation code has a habit of drifting to the right. Check the account, and inside that check it is open, and inside that check the amount, and inside that check the balance. Four levels deep, the one line that actually does the work is hard to find, and each else sits far away from the if it belongs to.

A guard clause fixes this. Instead of wrapping the good case in more and more ifs, you check for each problem first and return straight away. Whatever is left at the bottom is the happy path. In this tutorial you will write a money-transfer check both ways and prove the two versions agree. You need to know how if, return and objects work.

The rules

A transfer is allowed only if all of these hold:

  1. There is an account.
  2. The account is open (active is true).
  3. The amount is a positive whole number of kobo.
  4. The amount is no more than the balance.

Each failure should say which rule failed, so the function returns an object like { ok: false, why: 'bad amount' }. A success returns { ok: true, left: ... } with the remaining balance.

Early return in one sentence

return ends the function immediately. Nothing after it runs. So once a guard has returned an error, the lines below it can assume that rule passed.

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

91 Guard clauses instead of nested ifs

easy

Validate a transfer in kobo: there must be an account, it must be open, the amount must be a positive whole number, and it must not exceed the balance. Write it nested, then rewrite it as guards that return early, and prove the two agree.

Stuck? Three hints, smallest first
  1. 1. Handle each failure as it arises and return. One line per rule.
  2. 2. The happy path ends up last, at the left margin, with nothing wrapped around it.
  3. 3. Compare the two versions across every case rather than trusting the rewrite.

Step 1: the nested version

This is how the rules often get written the first time:

Step 1

function transferNested(amountKobo, balanceKobo, account) {
  if (account) {
    if (account.active) {
      if (Number.isInteger(amountKobo) && amountKobo > 0) {
        if (amountKobo <= balanceKobo) {
          return { ok: true, left: balanceKobo - amountKobo };
        } else {
          return { ok: false, why: 'insufficient funds' };
        }
      } else {
        return { ok: false, why: 'bad amount' };
      }
    } else {
      return { ok: false, why: 'account closed' };
    }
  } else {
    return { ok: false, why: 'no account' };
  }
}
const live = { name: 'Adaeze', active: true };
console.log(transferNested(500_00, 2000_00, live)); // { ok: true, left: 150000 }

It works. 500_00 is 50,000 kobo (₦500); the underscore only helps you read it. But the success line is four ifs deep, and the message 'no account' is at the very bottom, far from the if (account) that it answers.

Step 2: flip each rule into a guard

Take the first rule. Instead of "if there is an account, carry on inside", write "if there is no account, stop":

JavaScript

function transfer(amountKobo, balanceKobo, account) {
  if (!account) return { ok: false, why: 'no account' };
  // from here on, account exists
}

! means "not". Now do the same for each rule, one line each.

Step 3: the guard version

Step 3

function transfer(amountKobo, balanceKobo, account) {
  if (!account) return { ok: false, why: 'no account' };
  if (!account.active) return { ok: false, why: 'account closed' };
  if (!Number.isInteger(amountKobo) || amountKobo <= 0) return { ok: false, why: 'bad amount' };
  if (amountKobo > balanceKobo) return { ok: false, why: 'insufficient funds' };
  return { ok: true, left: balanceKobo - amountKobo };
}
const live = { name: 'Adaeze', active: true };
const closed = { name: 'Bola', active: false };
console.log(transfer(500_00, 2000_00, live).left);  // 150000
console.log(transfer(0, 2000_00, live).why);        // bad amount
console.log(transfer(2.5, 2000_00, live).why);      // bad amount
console.log(transfer(5000_00, 2000_00, live).why);  // insufficient funds
console.log(transfer(500_00, 2000_00, closed).why); // account closed
console.log(transfer(500_00, 2000_00, null).why);   // no account

It reads like the list of rules. Each problem sits next to its answer. The success case is the last line, with nothing wrapped around it.

Look at the third guard. The nested version said "is a whole number and above 0". Flipped, that becomes "is not a whole number or is 0 or less". When you turn a rule around, && becomes || and > becomes <=. This is where rewrites usually go wrong, which is why the next step matters.

Step 4: order is part of the design

The guards must run in this order. If you checked !account.active before !account, then a null account would make account.active throw a TypeError, because you can't read a property of null. In the guard version that order is easy to see, from top to bottom.

Step 5: prove the two agree

Never trust a rewrite by eye. Run both versions on every kind of case and compare:

Step 5

function transferNested(amountKobo, balanceKobo, account) {
  if (account) {
    if (account.active) {
      if (Number.isInteger(amountKobo) && amountKobo > 0) {
        if (amountKobo <= balanceKobo) return { ok: true, left: balanceKobo - amountKobo };
        else return { ok: false, why: 'insufficient funds' };
      } else return { ok: false, why: 'bad amount' };
    } else return { ok: false, why: 'account closed' };
  } else return { ok: false, why: 'no account' };
}
function transfer(amountKobo, balanceKobo, account) {
  if (!account) return { ok: false, why: 'no account' };
  if (!account.active) return { ok: false, why: 'account closed' };
  if (!Number.isInteger(amountKobo) || amountKobo <= 0) return { ok: false, why: 'bad amount' };
  if (amountKobo > balanceKobo) return { ok: false, why: 'insufficient funds' };
  return { ok: true, left: balanceKobo - amountKobo };
}
const live = { name: 'Adaeze', active: true };
const closed = { name: 'Bola', active: false };
const cases = [
  [500_00, 2000_00, live],
  [0, 2000_00, live],
  [2.5, 2000_00, live],
  [5000_00, 2000_00, live],
  [500_00, 2000_00, closed],
  [500_00, 2000_00, null],
];
const bothAgree = cases.every(
  ([a, b, c]) => JSON.stringify(transfer(a, b, c)) === JSON.stringify(transferNested(a, b, c)),
);
console.log(bothAgree); // true

There is one case per rule, plus the success. JSON.stringify turns each result into text, so two objects with the same contents compare as equal. (Comparing the objects directly with === would always be false, because they are two different objects.)

The full solution

The answer panel has both versions, runs them over all six cases, and checks that they agree and that each rule gives its own reason. It also shows that a bare return; hands back undefined. Press Run to see the output.

The answer

// The nested version. The line that does the work is five levels deep.
function transferNested(amountKobo, balanceKobo, account) {
  if (account) {
    if (account.active) {
      if (Number.isInteger(amountKobo) && amountKobo > 0) {
        if (amountKobo <= balanceKobo) {
          return { ok: true, left: balanceKobo - amountKobo };
        } else {
          return { ok: false, why: 'insufficient funds' };
        }
      } else {
        return { ok: false, why: 'bad amount' };
      }
    } else {
      return { ok: false, why: 'account closed' };
    }
  } else {
    return { ok: false, why: 'no account' };
  }
}

// The same rules as guards. Each failure is dealt with and left behind.
function transfer(amountKobo, balanceKobo, account) {
  if (!account) return { ok: false, why: 'no account' };
  if (!account.active) return { ok: false, why: 'account closed' };
  if (!Number.isInteger(amountKobo) || amountKobo <= 0) return { ok: false, why: 'bad amount' };
  if (amountKobo > balanceKobo) return { ok: false, why: 'insufficient funds' };

  return { ok: true, left: balanceKobo - amountKobo };
}

function nothing() {
  return;
}

const live = { name: 'Adaeze', active: true };
const closed = { name: 'Bola', active: false };

const cases = [
  [500_00, 2000_00, live],
  [0, 2000_00, live],
  [2.5, 2000_00, live],
  [5000_00, 2000_00, live],
  [500_00, 2000_00, closed],
  [500_00, 2000_00, null],
];
const bothAgree = cases.every(([a, b, c]) => same(transfer(a, b, c), transferNested(a, b, c)));

console.log(cases.map(([a, b, c]) => transfer(a, b, c)));

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('a good transfer, with the balance left over', transfer(500_00, 2000_00, live), { ok: true, left: 150000 });
test('the guards agree with the nested version on every case', bothAgree, true);
test('zero is not a transfer', transfer(0, 2000_00, live).why, 'bad amount');
test('nor is two and a half kobo', transfer(2.5, 2000_00, live).why, 'bad amount');
test('more than the balance is refused', transfer(5000_00, 2000_00, live).why, 'insufficient funds');
test('a closed account never reaches the amount check', transfer(500_00, 2000_00, closed).why, 'account closed');
test('and no account at all is caught first', transfer(500_00, 2000_00, null).why, 'no account');
test('a bare return hands back undefined', nothing(), undefined);

Both functions implement the same four rules and the assertion proves it, so the choice is purely about reading. The nested version buries the one interesting line under four ifs and pairs every condition with an else a screen away; the guards read as a list of rules, each with its answer beside it, and the success case sits at the bottom unindented.

Order matters and is part of the design: !account has to come before !account.active, or the second guard throws on null. That ordering is visible in the guard version and hidden in the nested one. The reward is that adding a fifth rule is one line rather than another layer, and it is why { ok, why } is worth returning instead of a bare false — the caller gets to say which rule failed.

Common mistakes

  • Flipping a condition wrong. "Whole and positive" turned around is "not whole or not positive". Test both versions side by side.
  • Guards in the wrong order. Check that something exists before you read a property from it.
  • Returning a bare false. The caller can't tell which rule failed. Return a reason too.

Try it yourself

  1. Add a fifth rule: transfers above ₦100,000 (10,000,000 kobo) are refused with 'over limit'. Add it to transfer only, then add a case and see the comparison fail.
  2. Rewrite a function canVote(age, isCitizen) with nested ifs, then with guards.
  3. Change transfer so a missing balance (undefined) is refused with 'no balance'.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.