Break in switch()

Hello,

I have one question regarding this challenge:

In its Hint1, it says:

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

I wonder why “break” shouldn’t be used here?

const authReducer = (state = defaultState, action) => {
  // Change code below this line
  switch (action.type) {
    case 'LOGIN': return {
      authenticated: true,
    };
     // break;            // why break shouldn't be present here?
    case 'LOGOUT': return {
      authenticated: false,
    };
    // break;            // why break shouldn't be present here?
    default: return defaultState;
  } 
  // Change code above this line
};

If the case fits only one of the cases listed above, it should have no harm if “break” was present, right?

Thank you.

You break out of the switch statement by using return. So there is no need for break here.

If you were to use break like this, you wouldn’t return any value, because you exit before returning the value.

case "LOGOUT":
      break;
      return {
        authenticated: false
      };

In this case on the other hand, break is unreachable code - it will never be called - because you return something - and by doing that you exit the switch statement.

case "LOGOUT":
      return {
        authenticated: false
      };
      break;
1 Like

the return statement gives an output to the function, and stops the function, so there is no need to have the break statements too

1 Like

Thank you for the answer!
so adding break here should have no harm since it is unreachable anyways, right?
I am just wondering why Hint1 says “don’t use break commands” here, which sounds a big thing to watch out.
It leads me to think that having “break” here could change the functionality… but in fact, it doesn’t matter.

to write good code, one of the various things, is to never write something that is never used

1 Like

It would cause no harm - yes, in the sense that it is not going to break your program. But just like @ilenia said, if this code is not going to be used, there is no point writing it :wink:

1 Like

I see. Thank you guys! :wink: