Switch statement used for multiple way decision making. It checks the value and execute the matching case blocks.
It is compared with each case using strict equality (===), Matching case runs, break stops execution and If no match → default runs. A switch statement can only have one default clause.
Syntax:
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}
Example:
let a = 10;
let b = 5;
let operator = "%";
switch (operator) {
case "+":
console.log(a + b);
break;
case "-":
console.log(a - b);
break;
case "*":
console.log(a * b);
break;
case "/":
console.log(a / b);
break;
default:
console.log("Invalid operator");
}
output : Invalid operator
In this example, that module operator is not in this case so it takes default value as a Invalid operator.
Top comments (0)