DEV Community

loading...
Cover image for Clean code - Guard clauses

Clean code - Guard clauses

Rémi Mayeux
・1 min read

What are guard clauses?

Instead of putting code inside an if-else statement, guard clauses are an early exit for cases that shouldn't run this code.

Use Case:

Nested if-else statements can get pretty messy, let's see a way to refactor one by using guard clauses.

// Without guard clauses
function processOrder(order, userId) {
  let result;
  if (order.userId === userId) { 
    if (order.status !== "DELETED") {
      result = await updateOrder(order);
    } else {
      result = await deleteOrder(order)
    }
  } else {
    throw new ForbiddenException();
  }
  return result;
}
Enter fullscreen mode Exit fullscreen mode
// With guard clauses
function processOrder(order, userId) {
  if (order.userId !== userId) throw new ForbiddenException();
  if (order.status === "DELETED") return deleteOrder(order)
  return updateOrder(order);
}
Enter fullscreen mode Exit fullscreen mode

This results in each logic block being separated and not a single if-else statement being used.

Conclusion

Guard clauses are one of the most efficient ways to make code easier to read, every time you use an if-else statement, you should ask yourself: can it be done with guard clauses?

Discussion (0)