Why should we not use breaks in these switch statement?

Tell us what’s happening:

Hey,

The solution of this challenge gives a tip to not use:

Tip: Make sure you don’t use “break” commands after return statements within the switch cases.

I did use them in my solution and it passed the tests. I’m not quite understanding why would we not use them there?

Thank you

Your code so far


const defaultState = {
authenticated: false
};

const authReducer = (state = defaultState, action) => {
// change code below this line
switch(action.type) {
  case 'LOGIN':
    return state = { authenticated: true };
    break;
  case 'LOGOUT':
    return state = { authenticated: false };
    break;
  default:
    return state;
}
// change code above this line
};

const store = Redux.createStore(authReducer);

const loginUser = () => {
return {
  type: 'LOGIN'
}
};

const logoutUser = () => {
return {
  type: 'LOGOUT'
}
};

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36.

Challenge: Use a Switch Statement to Handle Multiple Actions

Link to the challenge:

There’s technically nothing wrong with putting them there, but because the execution of the function ends at the return statement, there’s really no point in putting anything underneath them. It’s no different than something like this:

function add(x, y) {
  return x + y;
  console.log('I WILL NEVER BE RUN');
}
3 Likes

Nothing wrong per se, but a linter would flag it as unreachable code.

2 Likes