Use early returns and guard clauses instead of nested if-else statements to improve code readability and reduce complexity. Apply the fail-fast principle by handling edge cases and invalid conditions first, then proceeding with the main logic.
Benefits:
Examples:
Instead of:
const isCancellationReasonRequired = () => {
if (!props.teamCancellationSettings) {
return props.isHost;
}
if (props.isHost) {
return props.teamCancellationSettings.mandatoryCancellationReasonForHost;
} else {
return props.teamCancellationSettings.mandatoryCancellationReasonForAttendee;
}
};
Prefer:
const isCancellationReasonRequired = () => {
if (!props.teamCancellationSettings) {
return props.isHost;
}
if (props.isHost) return props.teamCancellationSettings.mandatoryCancellationReasonForHost;
return props.teamCancellationSettings.mandatoryCancellationReasonForAttendee;
};
For conditional rendering, handle the simpler/shorter condition first:
// Instead of lengthy if-else blocks
{!schedule?.timeBlocks?.length ? (
<SimpleComponent />
) : (
<ComplexComponent />
)}
Enter the URL of a public GitHub repository