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?
As the tutorial states
The
defaultkeyword specifies the code to run if there is nocasematch
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With