Return Early
A pattern you will see with many of the functional programming principles is to return early from a function. This pattern can be seen with early return, guard clauses, and continue statements.
Early Return
Early return, as the name suggests, is a pattern where you check for certain conditions and return from the function early. Take the following example:
function isBigEnough(number) {
if (number >= 10) {
return true;
} else {
return false;
}
}This function can be refactored to:
function isBigEnough(number) {
return number >= 10;
}Guard Clauses
Guard clauses are similar to early returns, but are used to check for invalid input. A guard clause is placed at the start of a function, and if the input does not meet the criteria, it will return early.
function withdraw(amount) {
if (amount > account.balance) {
return;
}
account.balance -= amount;
return amount;
}Continue
The continue statement can be used to return early from a loop. It will skip the rest of the loop and continue with the next iteration.
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) {
continue;
}
console.log(i);
}