Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unreachable code error when I use a break in my switch statement

I am wondering what I am doing wrong in my code. I am trying to do the following:

switch (action.type) {
    case TYPES.ADD_TO_FAVORITES:
      if (state.faves.length <= 10) {
        return assign({}, state, {
          faves: state.faves.concat(action.payload),
          full: false
        });
      } else {
        return assign({}, state, {
          faves: state.faves,
          full: true
        });
      }
    default:
      return state;
  }

My linter says to add a break before default case, but when I do that, it says unreachable code.

like image 584
user6701863 Avatar asked Nov 09 '22 10:11

user6701863


1 Answers

The linter rule i.e. 'no-fallthrough' in eslint, acts as to not allow any accidental fallthrough from case to case.

Meaning without break code execution will continue from matching case to next cases unless a break, return etc is encountered.

Sometimes we do need this but unintentional fallthrough can happen and this rule tries to prevent that.

You can disable the rule or configure it as warning . I would recommend to have a variable assigned for return value and at the end of the function and return it without disabling the rule.

function() {
var returnvalue;
Switch(variableA) {
    Case 1:
        returnvalue = somevalue;
        break;
    case 2:
        returnvalue = some other value;
        break;
     default:
         returnvalue= default value;
    }
return returnvalue; 

}

And for the unreachable part, you are returning from your if else block.

So the break will never get any chance to execute.

like image 158
Moniruzzaman Monir Avatar answered Nov 14 '22 21:11

Moniruzzaman Monir