Hey! What's going on everybody π
Welcome back to Web Dev Distilled π€©.
In the previous article, we've already talked about why you should not overuse switch
statement and some alternative approaches you can take to get rid of this statement from your code.
This article is the following up with the If Else
statement.
The Problem
When working with any programming language, we always have to deal with control flow (conditional statements).
In some scenarios, you can end up having a very long if-esle
(hell) or switch
statements, that hurt the readability, make our codebase too verbose and less clean.
In this article, I will show you some alternatives that you can consider using as a replacement for the if statements from your code.
Ternary Operator
Before
function validateUser(user) {
if (!user.name) {
return 'username cannot be empty!'
} else if (!user.password) {
return 'password cannot be empty'
} else {
return user
}
}
After
function validateUser(user) {
return !user.name ? 'username cannot be empty!'
: !user.password
? 'password cannot be empty'
: user
}
Using Logical Operator (Short Circuit)
Foundation Knowledge
This approach leverages the power of these below logical operators
1) The &&
AND operator will be evaluated only if the First condition is TRUE, in other words, it going to skip the ALL TRUTHY value and Stop at the FALSY value.
If no falsy value is found in the chaining, it is going to return the last one.
false && '' && 'hi there'
// => False
true && 'hello' && false
// => false
true && 'hello there'
// hello there
2) The ||
OR operator will be evaluated only if the First condition is FALSE, in other words, it's going to skip the ALL FALSY value and Stop at the TRUTHY value.
If there is no truthy value is found in the chaining, it is going to return the last one.
true || 'John Doe'
// => true
false || null || undefined || '' || 0 || 123
// => 123
3) We have one more logical operator is nullish coalescing ??
The ??
operator will be evaluated only if the First condition is TRUE, in other words, it's going to skip the ALL FALSY value EXCEPT these values 0
, false
and empty string ' '
and Stop at the TRUTHY value.
Consider using this operator if you have the intent to treat 0
and ' '
as truthy values.
false ?? true
// => false
'' ?? 'hi'
// => ''
0 ?? 123
// 0
null ?? undefined ?? 0 ?? 123
// 0
Before using logical operator
function deliverOrder(order) {
if (order && !order.isDelivered){
const updatedOrder = {...order, isDelivered: true}
return updatedOrder
} else {
return 'There is no order or order not delivered yet!'
}
}
After
function deliverOrder(order) {
if (!order || order.isDelivered) return;
return order && !order.isDelivered && {...order, isDelivered: true}
}
Object look-ups
I already wrote about this technique in the previous article.
Make sure to check that out here.
Split a big function into smaller ones by their responsibility
By the way here is my article on the Single Responsibility Principle with JavaScript if you haven't heard about this principle yet.
Before
function checkOut(item) {
if (!item) {
return false
} else if (!checkStockAvailable(item)) {
pushError("This item is out of stock");
resetCart();
return false;
} else {
updateStock(item);
redirectToPaymentPage();
return true;
}
}
After
function checkOut(item) {
const isOutOfStock = !checkStockAvailable(item);
return isOutOfStock ? markOrderIsOutOfStockAndResetCart()
: processToPayment()
}
function markOrderIsOutOfStockAndResetCart() {
pushError("This item is out of stock");
resetCart();
return false;
}
function processToPayment() {
updateStock(item);
redirectToPaymentPage();
return true;
}
function checkStockAvailable(item) {...} // return true or False
Early returns, less nested code
This is one of my favorite technique π
Before
function login(user) {
if (user && user.email && user.password) {
const userProfile = getUserProfile(user.email)
if (userProfile) {
if (userProfile.password === user.password) {
return setUserProfile(userProfile)
} else {
return pushError("Password does not match")
}
} else {
return pushError("User does not exist!")
}
} else {
return pushError("Please provide Email and Password!!")
}
}
After
function login(user) {
if (!user || !user.email || !user.password) {
return pushError("Please provide Email and Password!!")
}
const userProfile = getUserProfile(user.email);
if (!userProfile) return pushError("User does not exist!");
if (userProfile.password !== user.passsword) return pushError("Password does not match");
return setUserProfile(profile);
}
Thanks for spending time reading this article, I hope that you get some value out of it.
See you in the next one soon. π