← 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:
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:
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:
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? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.

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.