JavaScript/TypeScript S1854 False Positive

Hi, I’m using SonarLint inside VS Code. I believe I’m getting a false positive on S1854 - Remove this useless assignment to variable “$VARIABLE_NAME” when using Array.prototype.reduce(). The variable previousValue is falsely flagged as unused by SonarLint as it is returned by the reduce function.

For example:

const array = Array.from({ length: 20 }, (v, i) => i);
const sum = array
    .reduce((previous, current) => (previous += current), 0); // Remove this useless assignment to variable "previous".sonarlint(typescript:S1854)

Hello Patrick,

Welcome to SonarSource community, and thank you for your message!

It’s rather debatable whether the issue raises by S1854 is a false positive or not here. In a sense, that’s true that the value of previous is used in the body of your arrow function, but that’s a consequence of the side effect of the += operator which makes the code misleading in this particular snippet.

The assignment is indeed useless because you can get the same result by getting rid of the side effect as follows:

const sum = array.reduce((previous, current) => (previous + current), 0);

In light of the above, and although we are dealing with a border line case, I don’t consider it to be a false positive.

Hope this helps,
Yassin

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.