← Back toFront-end tips

Early return

Written byPhuoc Nguyen
Created
21 Mar, 2021
Category
Practice
Tags
JavaScript
Using the `if` statement is a common technique to deal with conditional logics. The code flow is split into different branches based on a given logic.
Let's take a look at a simple function that suffixes a given hour number with am or pm. The suffix is determined based on which range the hour belongs to as you can see in the following table:
HourWith suffix
012am
1 - 111am - 11am
1212pm
13 - 231pm - 11pm
An initial implementation of the function could look like:
js
const suffixAmPm = (hour) => {
if (hour === 0) {
return '12am';
} else {
if (hour < 12) {
return `${hour}am`;
} else {
if (hour === 12) {
return '12pm';
} else {
return `${hour % 12}pm`;
}
}
}
};
Imagine how the code looks like if we use multiple nested `if` statements. It's very hard to follow and maintain. Rather than using `else` or nested `if` statements, the function can return as soon as the condition matches:
js
const fn = (args) => {
if (condition) {
return 'foo';
} else {
// Long implementation
return 'bar';
}
};

// Better
const fn = (args) => {
if (condition) {
return 'foo';
}

// Long implementation
// Don't need to wrap within an `else`
return 'bar';
};
Using this practice, a new version of the `suffixAmPm` function looks like:
js
const suffixAmPm = (hour) => {
if (hour === 0) {
return '12am';
}

if (hour < 12) {
return `${hour}am`;
}

if (hour === 12) {
return '12pm';
}

return `${hour % 12}pm`;
};

See also

If you found this post helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

Questions? 🙋

Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Ask me questions

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn