Introduction to the JavaScript Switch Case Statement
One of the most common home appliances is the switch. It is used to control the flow of electricity in a circuit and it is used to transit between the on and off state and it performs differently based on the state we switch it to. The light either on or off based on the action you perform on the switch.
in JavaScript, the switch case statement does just that too. The switch keyword is used to create more than one conditional statements which allow different code blocks to be executed based on different condition. it is often used to replace complicated if else statement.
Syntax
switch(expression){
case first_value:
stmt_1;
break;
case second_value:
stmt_2;
break;
case third_value:
stmt_3;
break;
default:
default_stmt;
}
Expression
The switch statement takes an expression and evaluates it and if the expression equals the value(first_value, second_value, etc.), the corresponding statements in each case is executed.
Break
This will stop the execution of code and case testing inside the block. The next code block in the switch statement will be executed if the break keyword is omitted.
Default_stmt
This will be executed if the expression does not match any of the values.
JavaScript Switch Case Example
The following example declares a variable named month whose value represents a month in a year. The code outputs the name of the month based on the value of the month variable by using the switch statement.
var month = 5;
var monthName;
switch (month) {
case 1:
monthName = 'January';
break;
case 2:
monthName = 'February';
break;
case 3:
monthName = 'March';
break;
case 4:
monthName = 'April';
break;
case 5:
monthName = 'May';
break;
case 6:
monthName = 'June';
break;
case 7:
monthName = 'July';
break;
case 8:
monthName = 'August';
break;
case 9:
monthName = 'September';
break;
case 10:
monthName = 'October';
break;
case 11:
monthName = 'November';
break;
case 12:
monthName = 'December';
break;
default:
monthName = 'Invalid Month';
}
console.log(monthName); // May
Sometimes, you will want the cases to share the same code blocks. The example below will guide you on how to do it.
var day = 3;
var text;
switch (day) {
case 1:
case 2:
case 3:
default:
text = "Looking forward to the Weekend";
break;
case 4:
case 5:
text = "Soon it is Weekend";
break;
case 0:
case 6:
text = "It is Weekend";
}
This example declares two variable named day and text with the day variable initialized. The code outputs the text based on the value of the day variable.
In conclusion, the switch statement allow one of many code blocks to be executed based on the value the expression takes.