typescript:S4043 is not triggered on return statements

I am using SonarQube for IDE with the latest versions of VS Code and the SonarQube extension. Not in connected mode. I have the following code:

const testSonar = () => {    
    const test1 = [1, 3, 2];
    const test2 = [1, 3, 2];

    for (const num of test1.sort()) {
      console.log(num);
    }

    return test2.sort((a, b) => a - b);
}

Sonar correctly flags test1.sort()for sonarqube(typescript:S4043)and asks me to move it to a separate statement or use .toSorted(). However, test2.sort()is a false negative. The array is sorted in place and then returned, so it can benefit from the same improvement of sorting in a separate statement or using .toSorted() instead.

I did not check, but the same issue might also apply for.reverse() vs .toReversed() and .splice() vs .toSpliced().

Hi @hb20007,

Thank you for the clear example. You are right that S4043 treats the two sort() calls differently. After reviewing the rule description, we found that the for...of report is the inconsistency.

The description explains the concern as assigning the array returned by sort(). In your loop, num receives each element, not the returned array. The direct return test2.sort(...) also makes no such assignment, so its lack of a report is expected.

We opened JS-2755 to track the loop fix. We are also clarifying the rule description with examples of both cases.

Thank you for pointing this out.
-Francois