In Javascript, the switch statement provides a way to handle multiple conditions more concisely than a series of if-else if statements.
The switch statement evaluates an expression, and based on the result, it executes the code associated with the matching case.
switch (expression) { case value1: // Code to be executed if expression === value1 break; case value2: // Code to be executed if expression === value2 break; // Additional cases as needed default: // Code to be executed if none of the cases match }
The "expression" is evaluated once and compared against the values of each "case" label.
If a match is found, the corresponding block of code is executed.
The "break" statement is used to exit the "switch" block after executing the code for the matching case. Without a "break", control will fall through to the next case, executing its code as well.
The "default" case is optional and is executed if no match is found between the expression and any of the case labels.
Here we are using `switch` statement to execute a block of code based on the `day` value.
let day = "Wednesday"; switch (day) { case "Sunday": console.log("Day is Sunday"); break; case "Monday": console.log("Day is Monday"); break; case "Tuesday": console.log("Day is Tuesday"); break; case "Wednesday": console.log("Day is Wednesday"); break; case "Thursday": console.log("Day is Thursday"); break; case "Friday": console.log("Day is Friday"); break; case "Saturday": console.log("Day is Saturday"); break; default: console.log("Invalid option passed"); }
Day is Wednesday
Each `case` block is associated with a specific value.
The `break` statement is used to exit the switch statement once a matching case is found. If we omit the `break`, the code will continue to execute the next case block even if the value doesn't match.
The `default` case is optional and serves as the default code block to be executed if none of the case values match the expression.
In the below example, we have omitted the `break` keyword from "Friday" case and due to omitting the `break` keyword it will continue to execute next `case` blocks until unless it found `break` keyword in any other `case`.
let day = "Wednesday"; switch (day) { case "Sunday": console.log("Day is Sunday"); break; case "Friday": console.log("Day is Friday"); case "Saturday": console.log("Day is Saturday"); break; default: console.log("Invalid option passed"); }
Day is Friday Day is Saturday