Taha

Simpler conditionals with Guard Clauses

Nested conditionals can make your code harder to read and change—especially if you nest them more than one level.

Below, I'll show an example of a function that returns a discount for the provided user.

  • It should give a 20% discount for all regular users.
  • But if the user has a premium membership, it will give a 40% discount.
  • Gold users take the highest discount: 60%.
  • If the user is banned, however, it should not give any discount.

Without guard clauses, I'll write this function like this:

function getDiscountForUser(user) {
  let result
  if (user.isBanned) {
    result = 0
  } else {
    if (user.isPremium) {
      result = 40
    } else {
      if (user.isGold) {
        result = 60
      } else {
        result = 20
      }
    }
  }
  return result
}

I'll show you below how guard clauses can make it much simpler. But first, what are guard clauses?

What are Guard Clauses?

Guard clauses are the checks you put at the beginning of a function to check for the unusual conditions.

A usual (or called normal) condition is the condition that represents most cases for the needed behavior—in this case it's regular users getting a 20% discount. Anything other than that is called an unusual condition.

Guard clauses also return immediately if true—preventing other conditions from running.

Here's how the same function looks but with guard clauses:

function getDiscountForUser(user) {
  if (user.isBanned) return 0
  if (user.isPremium) return 40
  if (user.isGold) return 60

  return 20
}

With the beauty of guard clauses, the function became way much easier to read and change.

Taha Shashtari

I'm Taha Shashtari, a full-stack web developer. Building for the web is my passion. Teaching people how to do that is what I like the most. I like to explore new techniques and tools to help me and others write better code.

Subscribe to get latest updates about my work
©2024 Taha Shashtari. All rights reserved.