No Constant Condition
ID |
javascript.no_constant_condition |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
JavaScript |
Tags |
dead-code, reliability |
Description
Reports if, while, do…while, for, and ternary expressions whose condition is a constant value known at parse time — a literal number, string, boolean, null, regex, or any object / array / template literal. The condition always evaluates to the same truthiness, so the branch is either dead code or an unconditional loop entry.
The idiomatic infinite-loop forms while (true) {…} and do {…} while (true) are explicitly permitted to keep the rule usable in real code bases. for (;;) {…} is also accepted because the condition slot is empty (no constant expression).
Rationale
-
if (false) {…}is dead code and almost always a leftover from debugging or a typo (the author meantif (flag === false)or similar). -
if ([]) {…}is more subtle: empty arrays and objects are truthy in JavaScript. The branch always runs, even though many developers expect the opposite. Using a literal as the condition is a known mistake. -
In a
forheader, a literal condition produces an infinite loop unless something inside breaks — the explicitwhile (true)form is clearer and is the form the rule allows.
// Bad
if (false) {
legacyCleanup(); // never runs
}
if ([]) { // always runs — empty arrays are truthy
reset();
}
const flag = (true) ? "on" : "off"; // ternary always picks the first branch
Remediation
Replace the constant with the actual variable, expression, or feature flag the author intended. For intentional infinite loops, prefer while (true) {…} (which the rule allows) or for (;;) {…}.
// Good
if (config.legacyMode) {
legacyCleanup();
}
if (items.length === 0) {
reset();
}
const flag = settings.enabled ? "on" : "off";