Published on

Replacing if/else with Guard Clauses

Authors
  • avatar
    Name
    Nali Thephavong Haehn
    Twitter

Guard clauses (a.k.a. asserts or preconditions) are conditional statements at the beginning of a function that stops the execution of code when certain conditions are met allowing code to run faster and more efficiently with less lines of code. Are they necessary? No. Will your code still run? Well, yes, but writing clean, readable, and easy-to-maintain code should always be top priority (after working code, of course).

Let's Talk Code

Let's look at an example of proper refactoring of if/else statements into collections of guard clauses. Given this block of code:

const myPet = {
  type: "Dog",
  age: 7,
};

function isASeniorDog(myPet) {
  if (myPet.type === "Dog") {
    if (myPet.age >= 7) {
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }
}

The function can be rewritten using preconditions into this:

function isASeniorDog(myPet) {
  if (myPet.type !== "Dog") return false;
  if (myPet.age < 7) return false;
  return true;
}

You can see that it reduced the number of lines of code from 11 to 5 thus simplying our function and eliminating execution of unnecessary lines of code.