switch. If a
case statement does not have a
break;, the code for the next cases are also executed until a
break; is found. This is why the
break; statement is crucial when using the
switch statement. If the
break; statement does not exist, all the cases after the "correct" case are executed until the last case, including the default case. This defeats the purpose of the
switch statement as the statement is used when you have multiple outcomes and only want to pinpoint one outcome, not all of them.
The function of the
break; statement is to "break" out of the
switch statement and continue running the code below it. The
break; statement automatically exits the
switch statement after it is called, which is why the statements under one case are executed instead of executing all the statements. The code below shows an example of the
switch statement from the previous card without the
break; statement. Run the program and check out the statements printed in the console.
The sample code above prints all the log messages from "Wednesday" to the one inside the default case because the
break; statements do not exist. As mentioned above, if the
break; statements are missing, all the statements below the "correct" case are executed no matter what happens. The
switch statement will always exhibit this behavior, so make sure you use the
break; statement if necessary to avoid unwanted errors. Try adding the
break; statements above and see what happens.