In JavaScript, there are multiple ways to write conditionals. The first way most new developers get introduced to and get comfortable with is the “if statement”, “else statement” and the “else if” statement.
Hi 👋 and welcome to the third part of the mini-series of conditionals in JavaScript. In the last posts in the series I have shown you the basics of conditional statements and how to use them in your projects. With this third part, I will show you a way to make your code cleaner and more readable, let's get started!
When writing conditional logic statements they often turn into massive blocks of if... else if... else, and at the moment you write them they might seem all fine. But I have found that looking back on that code later can be troublesome since these big blocks of code can be hard to understand over time. And with that hard to debug. So how to change that? Let's have a look.
First of all: What is a guard clause?
"A guard clause is simply a single piece of conditional logic at the beginning of a function which will return from the function early if a certain condition is met" -Web Simplified
Hers is an example of how it may look:
// if, else statements
function userIsAdmin(user) {
if (user.role == 'admin') {
if (user.manager == true) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
So what did we just read? The function first checks if the object "user" is admin or not, if the user is admin and is manager the function will return true. If the "user" is not admin or not manager the function will return false. This is a common (but a bit simplified) pattern to check if the user has the privileges of an admin in an application. But here we have 13 lines of code that are hard to read for someone that might read it the first time or just doesn't know the logic that well beforehand. And if we would have even more possibilities it won't get easier and we might fall into "if/else hell"
One solution to this is using the guard clause, instead of multiple if/else if/else statements. Let's check it out:
function userIsAdmin(user) {
if (user.role != 'admin') return false
if (user.manager != true) return false
return true
}
}
Not too hard to understand right? So using the same if statements but without all the extra steps we here have the same function with only 6 lines of code. Great!
Using the != "not equal" or ! "logical not" our conditionals improve a lot.
But before you leave and start using this way to write your code with the guard clause, I just want you to know that most of the time its easier to start writing the logic as we have before with multiple if/else if/else statements, but when it's all working it's generally a good idea to refactor your code and rewriting the logic using the guard clause.
Liked what you read? Great, give me a thumbs up! 👍
Want to connect/give feedback? Awesome, write a comment below! 🏆