Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using break after default in switch statement when default not at end

In a w3schools tutorial on switch statements, it says:

If default is not the last case in the switch block, remember to end the default case with a break.

However, as that tutorial also states:

When JavaScript reaches a break keyword, it breaks out of the switch block.

So if you have a default with break at the beginning of a switch statement, why wouldn't the default always be executed and the block immediately exited by the interpreter? The interpreter doesn't read the items in the switch statement in order?

like image 517
nCardot Avatar asked Jun 07 '26 00:06

nCardot


1 Answers

As the tutorial states

The default keyword specifies the code to run if there is no case match

The position of the default keyword doesn't matter, the cases after it will be tested before executing the code in the default case. If one of those cases match, its code will be executed, so the break in the default block won't be executed.

The code after default is only executed if none of the explicit cases match, or the case before default is chosen and there's no break before default (so it falls through).

The default: case is usually written last by convention, so a break is not normally needed there. The warning in the tutorial is just a reminder that if you put default: earlier, the rule that you continue into the next case when there's no break still applies; there's nothing special about the default rule that would prevent it.

like image 135
Barmar Avatar answered Jun 09 '26 14:06

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!