Can we use break after return in JavaScript?

Continuing the discussion from freeCodeCamp Challenge Guide: Selecting from Many Options with Switch Statements:

Can we use break after return in JavaScript?
No, you don’t need a break after the return. Technically, anything after the return is unreachable code.

Hello there.

Do you have a question?

If so, please edit your post to include it.

Learning to describe problems is hard, but it is an important part of learning how to code.

Also, the more information you give us, the more likely we are to be able to help.

You should have at least 3 break statements

The test requires break statements which is why the second solution has both return and break. But yes, the breaks are unreachable code.

To clarify, the second example in the guide has returns followed by breaks. That’s the kind of thing that would make a code reviewer roll their eyes.

One or the other. Which is better? That depends. Personally, I would prefer to just return inside the case and not bother with the break. There is a different philosophy that you store the value in a variable and have just one return after the switch. (There is an old philosophy that a function should have only one return, but I think that is outdated.)

Which is better? They both are fine. But sometimes you work for a company that does something different. With every company I’ve worked (and even on different projects within the same company) I’ve had to adapt to their practices. Sometimes they will want things done a certain way. Think of this as one of those cases.

You might conceivably use both as well. So some of the cases return values and others set local values and break. I can’t really come up with a great use for it, other than maybe after some of the cases you need to do some extra processing inside the function the switch is in.

Yeah, I could see situations where different cases might do one or the other. I think that might be a code smell, but if it’s wrapped in a small function it could be OK.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.