There is another conditional statement known as the switch..case statement. It basically acts like a switchboard, as in it checks the input against predefined cases and if the input matches any case, then the code mentioned against that particular case is executed.
Syntax:
switch(variableToBeChecked) { case value1: // code to be executed when variableToBeChecked matches value1 break; case value2: // code to be executed when variableToBeChecked matches value2 break; case valueN: // code to be executed when variableToBeChecked matches valueN break; default: // code to be executed when variableToBeChecked doesn't match any case value }
Example:
var category = "women"; switch(category) { case "men": console.log("Showing men\'s apparels!"); break; case "women": console.log("Showing women\'s apparels!"); break; default: console.log("Showing all apparels!"); }
Output:
"Showing women\'s apparels!"
1. The curly braces are optional to be written in switch..case statement even if there are multiple statements to be executed inside a case.
2. The break statement is used to break the control out of the switch block when the value of a case matches; otherwise the code written inside all the subsequent cases after the matched case is executed. The last case does not need any break statement.
3. The default case is written in order to accommodate the scenario when none of the case value matches. It is generally written as the last case (but can be written earlier too).
Watch the video given below to learn the above properties of the switch..case statements.
break statement does exactly what its name says, it breaks out of the switch block. Break statement escapes from the curly braces that are enclosing the switch statement and lands you on the next command after the switch block.