Last updated on February 22, 2023
Switch case compares (evaluates) the two values and runs the code in the scope. It works the same as the If and else condition.
For example, we have to compare a statement in many cases instead of using if else conditions the switch case is cleaner and faster.
const fruit = "Apple";
if (fruit === "Apple") {
console.log("buy 2 kg");
} else if (fruit === "Orange") {
console.log("buy 2 dozen");
} else if (fruit === "banana") {
console.log("buy 1 dozen");
}else {
console.log("buy some dry fruits");
}
Above we have a few statements that check if the variable value matches with the specified value. For example, if the fruit variable’s value matches then allow to buy 2 kg. Similarly, further statements check and allow accordingly.
To do the same task we can use a switch case, in which each will have a condition that will be either true or false.
const fruit = "Apple";
switch (fruit) {
case "Apple":
console.log("buy 2 kg");
break;
case "orange":
console.log("buy 2 dozen");
break;
case "banana":
console.log("buy 1 dozen");
break;
default:
console.log("buy some dry fruits");
break;
}
The above switch case syntax evaluates an expression in each case.
As you see, in this switch case we have four cases, which compare the specified value with the fruit variable’s value. In case the value matches the switch case will execute that specific code block only. Also, it has a default case, it runs when all cases fail.