Early Return
Early Return is a pattern that suggests we avoid nested if-else
statements by checking the preconditions and return or throw as early as possible. Usually, Early Return is also called Gaurd Clause or Bouncer Pattern.
Contrived Example
// Before
function doSomething(user, data) {
if (hasPermission(user)) {
if (isNetworkAvailable()) {
if (isValid(data)) {
sendToServer(user, data);
} else {
throw new DataInvalidError();
}
} else {
saveInQueue(user, data);
}
} else {
throw new PermissionDeniedError();
}
}
to
function doSomething(user, data) {
if (!hasPermission(user)) {
throw new PermissionDeniedError();
}
if (!isNetworkAvailable()) {
saveInQueue(user, data);
return;
}
if (!isValid(data)) {
throw new DataInvalidError();
}
sendToServer(user, data);
}
It's helpful
- in keeping our code readable and understandable
- as it offloads the burden in our mind when dealing with complex conditions
Reference link: javascript.plainenglish.io/early-return-wit..