Deeply Nested if
ID |
javascript.nested_if |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Complexity |
Language |
JavaScript |
Tags |
code-style, complexity |
Description
Reports an if statement whose nesting depth (count of enclosing if statements within the same function) exceeds the configured threshold (default 4):
function classify(x) {
if (x > 0) {
if (x > 10) {
if (x > 100) {
if (x > 1000) {
if (x > 10000) { ... } // FLAW (depth 5 with limit 4)
}
}
}
}
}
Rationale
Each level of if nesting multiplies the mental cost of reading the function. A reader has to track which condition holds at every line, and the indentation alone consumes screen real estate. Past a small number of levels, the function is almost always doing too much: the cure is one of:
-
early-return / guard clauses,
-
extracted helper functions,
-
a lookup table or pattern-matching helper,
-
polymorphism (one method per case).
Remediation
Flatten with early returns:
function classify(x) {
if (x <= 0) return "zero or negative";
if (x <= 10) return "small";
if (x <= 100) return "medium";
if (x <= 1000) return "large";
if (x <= 10000) return "very large";
return "huge";
}
Or extract:
function classify(x) {
if (x <= 0) return "zero or negative";
return classifyPositive(x);
}
Notes
else if chains are <em>not</em> counted as nesting — they are sequential branches, not deeper ones. Only if`s inside the body of another `if (or its else block) count toward the depth. The threshold is configurable via the maxDepth rule property.
This rule is narrower than cyclomatic_complexity; the two are complementary — cyclomatic_complexity catches branchy functions in general, nested_if catches the "pyramid of doom" specifically.