Using guards to clean up your code

February 4th 2022 on Dušan's blog

I'm surprised at how many programmers don't know about guards. Simply put a guard is a boolean expression that must evaluate to false to continue the execution of a program in the main branch, otherwise the program returns early.

Think of it as a bouncer in front of a night club. If you don't meet the conditions of entrance, the bouncer won't allow you to enter.

Since an example is worth a thousand words, this is what you're not supposed to do.

const doSomething = (argument: number): number => {
  if (argument < 10) {
    if (argument > 0) {
      return argument;
    } else {
      return 0;
    }
  } else {
    return 10;
  }
};

The nested if statements make the code hard to read. Guards to the rescue! We can test each case individually and return early if the conditions are met.

const doSomething = (argument: number): number => {
  if (argument >= 10) {
    return 10;
  }

  if (argument > 0) {
    return argument;
  }

  return 0;
};

Now that every case is separated visually and there's no nesting the code is much, much easier to read and understand.

A small change can go a long way, this is a simple improvement that you can make to your code that'll definitely more than pay-off in the long run.