Else After Always-Exiting If
ID |
javascript.no_else_return |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
JavaScript |
Tags |
best-practice, code-style |
Description
Reports if (…) { … } else { … } where the if branch always exits via return, throw, break, or continue. The else adds indentation without changing behaviour — the same code can run after the if block at column zero, keeping the happy path level with the rest of the function.
Rationale
-
The early-return idiom — guard with
if, return, then continue with the happy path — is the convention in modern JavaScript style guides. -
Wrapping the happy path in
elseafter a guardedreturnflattens code unnecessarily and obscures which branch is the precondition.
// Bad - extra indentation for no behavioural reason
function classify(x) {
if (x > 0) {
return "pos";
} else {
return "non-pos";
}
}
Remediation
Drop the else and let the happy path follow the guard at the same level.
// Good
function classify(x) {
if (x > 0) {
return "pos";
}
return "non-pos";
}