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:
Hour | With suffix |
---|---|
0 | 12am |
1 - 11 | 1am - 11am |
12 | 12pm |
13 - 23 | 1pm - 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
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 🥷.
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