Early return

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