All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.javascript.rules.javascript.S3616.html Maven / Gradle / Ivy

There is a newer version: 5.0.0.6962
Show newest version

Why is this an issue?

The use of the comma operator and logical OR (||) operator within switch cases is not recommended. The switch statement is designed to evaluate a single expression and compare it against multiple values. When you use the comma operator or logical OR operator within a case, you’re essentially trying to match multiple values or conditions simultaneously: only the rightmost value will ever be considered with the comma operator, and the first truthy operand will be handled with the logical OR operator.

This behavior is not well-defined and can lead to unexpected results.

switch (a) {
  case 1, 2:   // Noncompliant: only 2 is matched by this case
    doTheThing(a);
  case 3 || 4: // Noncompliant: only 3 is matched by this case
    doThatThing(a);
  case 5:
    doTheOtherThing(a);
  default:
    console.log('Neener, neener!');
}

Using the comma operator or logical OR operator to combine multiple values or conditions within a single case can make the code more complex and difficult to read. It goes against the intention of the switch statement, which is to provide a concise and clear structure for branching based on a single value.

The switch statement should solely be used to rely on exact value matching instead.

switch (a) {
  case 1:
  case 2:
    doTheThing(a);
  case 3:
  case 4:
    doThatThing(a);
  case 5:
    doTheOtherThing(a);
  default:
    console.log('Neener, neener!');
}

The rule makes an exception for the switch (true) pattern, which is sometimes used as a workaround to achieve a similar effect to a series of if-else statements. This pattern allows you to evaluate multiple conditions acting as guards and execute corresponding code blocks based on the first matching condition.

function weekStatus (day) {
  let status;
  switch (true) {
    case (day === 'MON' || day === 'TUE' || day === 'WED' || day === 'THU' || day === 'FRI'):
      status = 'Weekday';
      break;
    case (day === 'SAT' || day === 'SUN'):
      status = 'Weekend';
      break;
  }
  return status;
}

Resources

Documentation





© 2015 - 2025 Weber Informatics LLC | Privacy Policy