Sonarjs/no-empty-collection eslint rule doesn't recognize usage of ||= assignment

  • What language is this for? JavaScript
  • Which rule? no-empty-collection (from eslint-plugin-sonarjs)
  • Why do you believe it’s a false-positive/false-negative? executing the code works fine but the rule reports a bug
  • How can we reproduce the problem? Give us a self-contained snippet of code (formatted text, no screenshots)

The bug can be reproduced in this dedicated repository: GitHub - DamienCassou/sonarjs-issue-no-empty-collection-logical-or-assignement: Reproduce an issue with sonarjs/no-empty-collection and logical OR assignment..

The problematic code is:

let strings = [];

// no-empty-collection reports an issue here. This is ok because the
// code below "expands" to `strings[1] = strings[1] || "foo"` and the
// 2nd `strings[1]` is noncompliant:
strings[1] ||= "foo";


// no-empty-collection reports an issue here. This is wrong because at
// this point strings[1] contains "foo":
if (strings[1]) {
  // Same here. Executing this program prints "foo" further confirming
  // that the `if` statement above is correct:
  console.log(strings[1]);
}

Hi Damien,

Welcome to the Sonar Community!

This is a great catch, thanks for taking the time to prepare and share this.

I created a ticket to fix the false positive:
https://sonarsource.atlassian.net/browse/JS-258

It seems the rule does not properly support the logical OR assignment operator. The detection is accurate for a normal assignment and also for the classic use of || for default values.

For reference, here’s your example analyzed in SonarCloud (I only changed the index to zero to keep it simple).

Thank you. Is there a way for me to subscribe to the issue on atlassian to be notified when it gets fixed?

Unfortunately, it is not possible at this time.

I added a comment in the ticket so that we ping you on this thread :+1:

1 Like