Using JavaScript Switch Case
The switch statement is used to execute different actions depending on different conditions. The switch evaluates the expression it receives and matches it with the appropriate case. The statement(s) matching the appropriate case are executed.
Spelling Rule
switch (expression) {
case value1: //Code that will be executed if the expression matches value1.
[break;]
case value2: //codes to be executed if expression matches value2.
[break;] ...
case value: //Code that will be executed if expression matches valueN.
[break;]
default: //codes to be executed if the expression matches no values.
[break;]
}
expression: the value to be matched with case values case valueN: word/value to be matched with the expression Definition: The expression indicates the situation to be matched with case values. If the expression matches one of the case values, break from the matching value; All codes up to the command are executed. If the break command is not used after the conditions, the program runs each case code downwards. The use of break is an important point that should not be forgotten.
Example 1:new Date().getDay() method 0- Generates values between 6. 0->market 6->indicates Saturday.
switch (new Date().getDay()) {
case 0:
day = "SUNDAY";
break;
case 1:
day = "MONDAY";
break;
case 2:
day = "TUESDAY";
break;
case 3:
day = "WEDNESDAY";
break;
case 4:
day = "THURSDAY";
break;
case 5:
day = "FRIDAY";
break;
case 6:
day = "SATURDAY";
}
Example 2:
function control() {
var text;
var fruit = document.getElementById("information").value;
switch(fruit) {
case "Watermelon"
text = "Watermelon is Beautiful!";
case "Pear"
text = "I don't like pears very much";
case "Cherry"
text = "Cherry is a sweet fruit with a short season";
default
text = "Sorry! I don't recognize the fruit you wrote";
}
document.getElementById("show").innerHTML = text ;
}
Example 3: Example of the error that will occur when you forget to write break
var value = 0;
switch (value) {
case -1:
alert("-1 negatslander.")
break;
case 0: // this section will work since the value is 0.
alert(0);
// NOTE: We forgot to write break.
case 1: // Since break is not written, the case will be run for the value 0 in this section.< /span>
alert(1);
break; // Case 2 value will not be executed because break is written.
case 2:
alert(2);
break;
default:
alert("default");
}
Example 4: You can use multiple case for a single action.
var fruit = 'Kiwi';
switch (fruit) {
case 'Apple':
case 'Quince':
case 'Kiwi':
case 'Watermelon':
alert("Yes, what you wrote is a fruit.")
break;
case 'Tomato':
default:
console.log('No, this is not a fruit');
}