jshint throws a"Expected a 'break' statement before 'case'"

JavascriptJshint

Javascript Problem Overview


Hi I am having a trouble when my framework is using jshint to validate my javascript code. I have used switch-case without a break statement intentionally, but this portion of code is captured as an error when jshint checks. My code is something like below.

    switch (<no>){
    case 1:
        // does something
    case 2:
        //does something more
    default:
        // does something even more
   }

Error from 'jshint' is like Line 203 character 41: Expected a 'break' statement before 'case'. Any thoughts on how to avoid it ? or is it a bad practice to use switch cases in this scenario at all ?

Javascript Solutions


Solution 1 - Javascript

Copy & paste from the documentation:

> Switch statements > > By default JSHint warns when you omit break or return statements within switch statements: > > [...] > > If you really know what you're doing you can tell JSHint that you > intended the case block to fall through by adding a /* falls through */ comment

So in your case:

switch (<no>) {
  case 1:
    // does something
    /* falls through */
  case 2:
    //does something more
    /* falls through */
  default:
    // does something even more
}

Solution 2 - Javascript

Exactly, breaks may be totally superfluous, like in this example

function mapX(x){
  switch (x){
    case 1:
      return A;
    case 2:
      return B;
    default:
      return C;
  }
}

In this case, if you would have had a break after return, JS Standard would throw a warning, namely Unreachable code.

Trying to conciliate jshint and JS Standard is tricky, but as stated, the solution would be

function mapX(x){
  switch (x){
    case 1:
      return A;
      /* falls through */
    case 2:
      return B;
      /* falls through */
    default:
      return C;
  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsakthisundarView Question on Stackoverflow
Solution 1 - JavascriptGerald SchneiderView Answer on Stackoverflow
Solution 2 - JavascriptJoão Pimentel FerreiraView Answer on Stackoverflow