Cognitive Complexity
Cognitive Complexity is the measure of how difficult the code is to understand. It depends upon the breaks in the linear flow of the code and nesting. It also depends upon unnecessary return statements, jumps and other code smells that makes the code hard to be understood. Cognitive complexity does not accounts for execution speed or time complexity, it just signifies the code readability.
What adds to complexity?
When any function doesn't performs any loop and is executed from top to bottom without iteration it does not adds up to complexity. Below is an example of code without any cognitive complexity.
In the given function the flow is linear from top to bottom linearly therefore nothing contributes to the cognitive complexity.
Lets look into the same code written in some other form.
The function does the same thing as above but it has higher cognitive complexity as there is a loop involved and same lines of code are executed more than once.
Apart from loops, conditions, try/catch, logical expressions, jumps, recursion also adds to cognitive complexity.
Nesting of conditionals, loops and try/catch adds further more to cognitive complexity.
Note : Using code reduction techniques specific to any language does not add to cognitive complexity. For ex using arrow operator in JS (=>) to define a function instead of function keyword will not any complexity.
Recommended by LinkedIn
Reducing Cognitive Complexity
As a developer we should always make sure the code is easier to read as this is the thing that really makes a difference between an senior developer and someone who is starting new.
A function can be made easily readable by follow in some simple points.
There could be many ways in which the readability of a code can be increased and this is what cognitive complexity accounts for. It has no effect on performance rather just it is helpful in writing codes that are compact, easy to read and understand.