Return Early Pattern
The Return Early Pattern
This:
function getErrorMessage(someObject) {
let errorMessage;
if (someObject && someOtherObject) {
errorMessage = "This isn't working because of a tornado.";
} else if (someObject || someOtherOtherObject) {
errorMessage = "You're not allowed to visit";
} else {
errorMessage = "I don't know what happened."
}
return errorMessage;
}
is not as readable as this:
function getErrorMessage(someObject) {
if (someObject && someOtherObject) {
return "This isn't working because of a tornado.";
}
if (someObject || someOtherOtherObject) {
return "You're not allowed to visit.";
}
return "I don't know what happened.";
}
- Performance is better (not that significant)
- Pattern only makes sense if return statements aren't scattered all over the place
Source: I learned this during code review at work.