Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statements: do you need the last break? (Javascript mainly)

When using a switch() statement, you add break; in between separate case: declarations. But what about the last one?

Normally I just leave it off, but I'm wondering if this has some performance implication I'm not thinking about?

I've been wondering about this for a while and don't see it asked elsewhere on Stack-O, but sorry if I missed it.

I'm mainly asking this question regarding Javascript, although I'm guessing the answer will apply to all switch() statements.

like image 469
Jon Raasch Avatar asked Apr 28 '10 13:04

Jon Raasch


People also ask

Do switch statements need break Javascript?

The break KeywordIt is not necessary to break the last case in a switch block. The block breaks (ends) there anyway. Note: If you omit the break statement, the next case will be executed even if the evaluation does not match the case.

Is it necessary to use break in every switch statement?

The break statement is used inside the switch to terminate a statement sequence. The break statement is optional. If omitted, execution will continue on into the next case. The default statement is optional and can appear anywhere inside the switch block.

Can the last case of a switch statement skip including the break?

Can the last case of a switch statement skip including the break? Even though the last case of a switch statement does not require a break statement at the end, you should add break statements to all cases of the switch statement, including the last case.

Do you need a break after a return in a switch statement?

Answer 533416ba631fe960060022a4 No. return jumps back directly to the function call returning the value after it and everything (in a function) that is after an executed return statement is ignored. So return itself can act as a break statement for functions and no further break is required.


1 Answers

Performance should not be a consideration at all. Even if some language or implementation has a performance difference that's measurable in a micro-benchmark, it would never cause a real-world performance issue.

I think the most important issue is consistency and maintainability. If you leave off the last break and then another developer adds another case statement without realizing you left off the break, the behavior would change. It's really the second developer's fault for not noticing the break is missing, but it could have been avoided by being consistent and having the break on all case clauses.

like image 165
Samuel Neff Avatar answered Oct 15 '22 22:10

Samuel Neff