Skip to content

How to reduce cognitive complexity of nested if

I have an if statement set up like this

if (A && B) {
   // do something 1
} else {
   if (B) {
      // set some boolean to false
   } 
   // do something 2
}

I’m wondering if I can lower the cognitive complexity? Right now this is a score of 4.

Answer

I would say the best way to lower the cognitive complexity is to use functions. This is similar to @GuerricP original answer, but handles the multiple case of do somthing 2

eg.

function doSomething2() {}

if (A && B) {
  // do something 1
} else if (B) {  
  // set some boolean to false
  doSomething2();
} else {
  doSomething2();
}

This reduces complexity, because it’s not obvious that there are 2 routes to doSomething2 in your original version.