Fall-through Behavior

The switch Statement

Fall-through Behavior

🙋 Need help? Ask an expert now!

JavaScript supports the fall-through behavior in 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.

Edit Me on GitHub!

Application Question

Consider the following code segment:

let sum = 20;
    case 10: console.log("a"); break;
    case 20: console.log("b");
    case 30: console.log("c"); break;
    case 40: console.log("d");
    case 50: console.log("e"); break;

What will the following code print to the console?