Let’s talk about a coding trick that makes your code easier to read and keeps things organized: early returns.
Lots of coders rely on if-else statements to check different conditions, but stacking them up can get messy. Instead, early returns let us handle all the error cases up front, so we can save the ideal scenario for the end of the function.
Example
Here’s a function that checks if a user can get a discount:
function getDiscountMessage(user) {
if (user.isActive) {
if (user.hasDiscount) {
return `Discount applied for ${user.name}!`;
} else {
return `${user.name} does not qualify for a discount.`;
}
} else {
return `User ${user.name} is inactive.`;
}
}
This code is filled with nested if-else statements. 🤮
Instead, we can cover the error cases first with early returns and then focus on the "perfect scenario" at the end:
function getDiscountMessage(user) {
if (!user.isActive) {
return `User ${user.name} is inactive.`;
}
if (!user.hasDiscount) {
return `${user.name} does not qualify for a discount.`;
}
// Perfect scenario: user is active and qualifies for a discount
return `Discount applied for ${user.name}!`;
}
Each error condition is handled in a single line right at the start. This keeps our code neat and straightforward, without all the if-else blocks of different nesting levels to follow.
So next time, skip the if-else and give early returns a try. 😎