A guard clause is a line of code that prevents the following block of code from running unless a certain condition is met.
Guard clauses are preferrable to nested conditionals because they are faster and simpler than nesting conditional statements.
- Replace nested Conditionals with Guard Clauses.
- Anti If Campaign.
- Prefer Guard Clauses over nested Conditionals.
- Refactoring nested Conditionals.
const obj = {
a: {
b: 'value of b!'
}
};
function findPropBOfObject (object) {
object.a || return;
return object.a.b;
}
function unguardedFindPropBOfObject (object) {
if (object.a && object.a.b) {
return object.a.b;
} else {
return;
}
}