Cognitive Complexity calculation for Typescript on '||' and '?'

Must-share information (formatted with Markdown):

  • which versions are you using (SonarQube, Scanner, Plugin, and any relevant extension)
    SonarLint v4.8.0 for vscode
  • how is SonarQube deployed: zip, Docker, Helm
    NA
  • what are you trying to achieve
    Cognitive complexity calculation for typescript on || and ?? is not always consistent.
    In the section ‘Exceptions’ of ‘why is this an issue’, an example is provided to illustrate ‘short circuit’ (‘||’) and ‘null coalescing’ (‘??’) should be considered as no cognitive complexity increase
function greet(name) {
    name = name || 'Guest';
    console.log('Hello, ' + name + '!');
}

but I find they are not ignored in some common cases which can be noisy for typescript cognitive complexity calculation

function testCognitiveComplexity()
{
    const name = null;
    const array = [name?? "Guest",name|| "Guest"]; // +2
    const composite = {p1 : name || 'Guest'}; // +
}

It seems they are only ignored when they are logical expression in ‘VariableDeclarator’ and ‘AssignmentExpression’ (code pointer)

Do we consider this as a bug?

  • what have you tried so far to achieve this
    N/A

Hello @Fei,

Welcome to the Sonar community, and thank you for your feedback!

How short-circuiting and null coalescing operate in JavaScript and TypeScript differs indeed from other languages. In fact, we tried to adjust the cognitive complexity rule to accommodate common idioms to some extent. However, as you pointed out, it doesn’t make sense for the rule to increase complexity when encountering these operators.

I have created a ticket to improve the rule in that regard, and we hope to address this soon.

Best regards,
Yassin

Thanks Yassin for the quick turn around! Looking forward to the fix.

@Yassin Can I ask what’s the status of the issue? We are using SonarQube especially Cognitive Complexity for typescript projects in our company, and this issue cause a number of false positives, would like to know if there is any plan to prioritize the fix? Appreciate it!

1 Like

Hello @Fei,

It seems that we forgot to include this change in the latest release of the JavaScript/TypeScript analyzer. Therefore, I just created a PR to address this issue, which the team will review as soon as possible.

Once this is merged, I can’t tell you exactly when this change will be released, but hopefully, it will be soon.

Cheers,
Yassin

1 Like

Thanks @Yassin for the code change! I see SQ just released v10.7 recently, can we expect this code change to be added to next version, i.e. v10.8?

1 Like

Yes, definitely!

2 Likes