Always Use Braces Around Control-Flow Bodies
ID |
javascript.control_statement_braces |
Severity |
info |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
JavaScript |
Tags |
code-smell, style |
Description
Reports if, else, while, do-while, for, for-in and for-of statements whose body is a single statement not wrapped in braces. The brace-less form is valid JavaScript syntax but a known maintenance trap: when a developer adds a second statement under what looks like the body, the new statement runs unconditionally because it never was inside the branch or loop.
Braces are required around every control-flow body, even single-statement bodies — the strict, no-exceptions form of the rule.
Rationale
// Bad — looks fine until someone adds the second line:
if (isAdmin)
grantAccess();
logAdminLogin(); // always runs, even for non-admins
The indentation lies. logAdminLogin() is not part of the if branch — it executes unconditionally. The same hazard exists for every loop and every else branch.
Other reasons to require braces:
-
Diffs are smaller and clearer when a single-statement body grows to two statements.
-
Automatic formatters and refactoring tools handle braced blocks more reliably.
-
Brace-less bodies interact awkwardly with the empty-statement and dangling-else hazards.
else if is itself another if statement and is therefore allowed without an extra pair of braces wrapping the inner if.
Remediation
Wrap every control-flow body in braces, even when the body is a single statement.
// Good
if (isAdmin) {
grantAccess();
}
if (cond) {
a();
} else if (other) {
b();
} else {
c();
}
while (cond) {
iter();
}
for (const x of xs) {
handle(x);
}
do {
f();
} while (cond);