The switch
statement is used to control the flow of a program and is a part of JavaScript’s conditional statements.
It allows the execution of a specific code block depending upon the evaluation of an expression.
switch
switch
keyword followed by the expression to be evaluated in parentheses.switch (expression){}
switch (expression){case value1:/* implement the statement(s) to be executed whenexpression = value1 */break;case value2:/* implement the statement(s) to be executed whenexpression = value2 */break;case value3:/* implement the statement(s) to be executed whenexpression = value3 */break;default:/* implement the statement(s) to be executed if expressiondoesn't match any of the above cases */}
The break
statement is used to exit the switch structure after the execution of a case. If it is not used, all the subsequent cases will be executed until the program encounters any break
statement or the ending curly brace }
of the structure.
The default:
is a special type of case and is executed when none of the cases match the evaluated expression.
The program will find out the day of the week based on the value of the day
variable.
Let’s look at the flow chart of this example for a better understanding:
Let’s look at the implementation of the example:
var day = 2; //change and try with different valuesswitch(day){case 1: //if day = 1console.log("Monday");break;case 2: //if day = 2console.log("Tuesday");break;case 3: //if day = 3console.log("Wednesday");break;case 4: //if day = 4console.log("Thursday");break;case 5: //if day = 5console.log("Friday");case 6: //if day = 6console.log("Saturday");case 7: //if day = 7console.log("Sunday");break;default: //if day doesn't match any of aboveconsole.log("Invalid");}