- 5 years ago
- Zaid Bin Khalid
- 6,807 Views
-
5
In this session, you will learn how to use the switch and case statement to test expression with different values in JavaScript with the help of syntax and example.
Using the Switch…Case Statement
The switch…case statement is used as an alternative statement to the if…else if…else statement; they almost work the same. The statement tests an expression or a variable against the series’s values until it finds a match. After that, it executes the block of code corresponding to that match.
The basic syntax of a switch…case, as shown below:
switch(x){
case value1:
// Code to be executed if x === value1
break;
case value2:
// Code to be executed if x === value2
break;
...
default:
// Code to be executed if x is different from all values
}
The following example will display the name of the day of the week.
var d = new Date();
switch(d.getDay()) {
case 0:
alert("Today is Sunday.");
break;
case 1:
alert("Today is Monday.");
break;
case 2:
alert("Today is Tuesday.");
break;
case 3:
alert("Today is Wednesday.");
break;
case 4:
alert("Today is Thursday.");
break;
case 5:
alert("Today is Friday.");
break;
case 6:
alert("Today is Saturday.");
break;
default:
alert("No information available for that day.");
break;
}
In one crucial way, the Switch…case is different from the if…else statement. The switch statement executes statement by statement or line by line. The JavaScript once find a case clause that evaluates to true, it does not only run the code corresponding to that case clause, but it also executes all the subsequent case clauses till the end of the switch block automatically.
To stop this, you must add a break statement after each case. The break statement will tell the JavaScript interpreter to break out of the switch…case statement block once it executes the code with the first true case.
In the case of the default clause, the break statement is not required when it finally appears in a switch statement. If another case statement is added to the switch statement, it prevents a possible programming error later. Although, it a good programming practice to terminate the last case or default clause in a switch statement with a break.
var d = new Date();
switch(d.getDay()) {
default:
alert("Looking forward to the weekend.");
break;
case 6:
alert("Today is Saturday.");
break;
case 0:
alert("Today is Sunday.");
}
Multiple Cases Sharing the Same Action
In a switch statement, each case value must be different from others or unique. Different cases don’t need to have a single action. Many situations can share the same work, as shown below:
var d = new Date();
switch(d.getDay()) {
case 1:
case 2:
case 3:
case 4:
case 5:
alert("It is a weekday.");
break;
case 0:
case 6:
alert("It is a weekend day.");
break;
default:
alert("Enjoy every day of your life.");
}
- 5 years ago
- Zaid Bin Khalid
- 6,807 Views
-
5