Skip to content

no-excessive-cognitive-complexity

Report an error for function bodies with cognitive complexity above 20.

Why

Nested control flow increases the context a reader must retain while following a function.

Fix

Scores up to 20 pass; 21 or more are errors. Examples are fictional; domain types are omitted. Refactor one function at a time, starting with its largest contributors. First simplify control flow and reduce nesting within the function. Extract a helper only when it clarifies a cohesive responsibility or enables meaningful reuse; do not split code solely to lower the score. Use lookup tables only for equivalent pure dispatch. Preserve APIs, side effects, evaluation order, and exception behavior. Run relevant tests before and after; remeasure the original and extracted functions. Do not hide branches in dense expressions or add indirection just to lower a score.

Examples

Before — flagged Synthetic catalog traversal: score 21 (error)
src/example.ts
function collectLabels(catalog: Catalog): string[] {
const labels: string[] = [];
for (const section of catalog.sections) {
for (const shelf of section.shelves) {
for (const item of shelf.items) {
if (item.visible) {
if (item.inStock) {
if (item.label !== "") {
labels.push(item.label);
}
}
}
}
}
}
return labels;
}
After — preferred Extract eligibility: traversal 10; predicate 3
src/example.ts
function hasDisplayLabel(item: CatalogItem): boolean {
if (!item.visible) return false;
if (!item.inStock) return false;
if (item.label === "") return false;
return true;
}
function collectLabels(catalog: Catalog): string[] {
const labels: string[] = [];
for (const section of catalog.sections) {
for (const shelf of section.shelves) {
for (const item of shelf.items) {
if (hasDisplayLabel(item)) labels.push(item.label);
}
}
}
return labels;
}
Before — flagged Synthetic download eligibility: score 21 (error)
src/example.ts
function canDownload(item: Download): boolean {
if (item.published) {
if (item.licensed) {
if (item.available) {
if (!item.quarantined) {
if (item.bytes > 0) {
if (item.bytes <= 1000000) {
return true;
}
}
}
}
}
}
return false;
}
After — preferred Use early returns: score 6
src/example.ts
function canDownload(item: Download): boolean {
if (!item.published) return false;
if (!item.licensed) return false;
if (!item.available) return false;
if (item.quarantined) return false;
if (!(item.bytes > 0)) return false;
if (!(item.bytes <= 1000000)) return false;
return true;
}
Before — flagged Seven nested decisions exceed the error limit
src/decision.ts
function decide(a, b, c, d, e, f, g) {
if (a) {
if (b) {
if (c) {
if (d) {
if (e) {
if (f) {
if (g) {
act();
}
}
}
}
}
}
}
}
After — preferred Guard clauses reduce nesting
src/decision.ts
function decide(a, b, c, d, e, f, g) {
if (!a) return;
if (!b) return;
if (!c) return;
if (!d) return;
if (!e) return;
if (!f) return;
if (!g) return;
act();
}