Javascript: Guard Clauses
Guard clauses are a great alternative to if…else statements. Reasons being that they help your create clean & easy to read code AND they guard the flow of logic from continuing if certain conditions are met, or not met. This is extremely beneficial as it increases the speed at which a function runs as well as reduces the number of lines in your functions and classes.
if…else statements usually start innocently but can quickly evolve into a hard to read chain. Here we are checking to see if an user is an admin in 13 lines.
function userIsAdmin(user) {
if (user.role == 'admin') {
if (user.manager == true) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
As you can see there is an if…else statement wrapped inside of another if…else statement which could definitely cause some issues if you needed to add more conditions. Below we have the same function refactored with the guard clause.
function userIsAdmin(user) {
if (user.role != 'admin') return false
if (user.manager != true) return false
return true
}
Beautiful! As you can see the function can now be completed in 3 lines and it is way easier to follow. This is especially helpful when you begin to wrap conditional functions inside of other functions. Hopefully this will be a helpful tip as you continue your growth as a dev.