src/content/docs/linter/rules/no-excessive-cognitive-complexity.mdx
import { Tabs, TabItem } from '@astrojs/starlight/components';
<Tabs> <TabItem label="JavaScript (and super languages)" icon="seti:javascript"> ## Summary - Rule available since: `v1.0.0` - Diagnostic Category: [`lint/complexity/noExcessiveCognitiveComplexity`](/reference/diagnostics#diagnostic-category) - This rule isn't recommended, so you need to enable it. - This rule doesn't have a fix. - The default severity of this rule is [**information**](/reference/diagnostics#information). - Sources: - Same as [`sonarjs/cognitive-complexity`](https://github.com/SonarSource/eslint-plugin-sonarjs/blob/HEAD/docs/rules/cognitive-complexity.md) - Inspired from [`complexity`](https://eslint.org/docs/latest/rules/complexity){
"linter": {
"rules": {
"complexity": {
"noExcessiveCognitiveComplexity": "error"
}
}
}
}
Disallow functions that exceed a given Cognitive Complexity score.
The more complexity a function contains, the harder it is to understand later on.
Reducing complexity helps to make code more maintenable, both by making it easier to understand as well as by reducing chances of accidental side-effects when making changes.
This rule calculates a complexity score for every function and disallows those that exceed a configured complexity threshold (default: 15).
The complexity score is calculated based on the Cognitive Complexity algorithm: https://redirect.sonarsource.com/doc/cognitive-complexity.html
function tooComplex() {
for (let x = 0; x < 10; x++) {
for (let y = 0; y < 10; y++) {
for (let z = 0; z < 10; z++) {
if (x % 2 === 0) {
if (y % 2 === 0) {
console.log(x > y ? `${x} > ${y}` : `${y} > ${x}`);
}
}
}
}
}
}
Allows specifying the maximum allowed complexity.
{
"linter": {
"rules": {
"complexity": {
"noExcessiveCognitiveComplexity": {
"options": {
"maxAllowedComplexity": 15
}
}
}
}
}
}
The allowed values range from 1 through 254. The default is 15.