switch
Statementswitch
Statement?The switch
statement in JavaScript is used to execute one block of code from multiple possible cases, based on the value of an expression. It is an alternative to multiple if...else
statements.
switch
Statementswitch (expression) {
case value1:
// Code to execute if expression === value1
break;
case value2:
// Code to execute if expression === value2
break;
default:
// Code to execute if no cases match
}
switch
Worksswitch
expression is evaluated.case
value.break
statement stops execution after a match is found.default
case (if present) executes.
switch
Statementlet day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
case 4:
console.log("Thursday");
break;
default:
console.log("Invalid day");
}
๐ Output: "Wednesday"
day = 3
, it matches case 3, so "Wednesday"
is printed.
default
Caselet color = "blue";
switch (color) {
case "red":
console.log("The color is Red.");
break;
case "green":
console.log("The color is Green.");
break;
default:
console.log("Unknown color.");
}
๐ Output: "Unknown color."
"blue"
doesn't match any case, the default
case executes.
let fruit = "apple";
switch (fruit) {
case "apple":
case "banana":
console.log("This is a fruit.");
break;
case "carrot":
console.log("This is a vegetable.");
break;
default:
console.log("Unknown item.");
}
๐ Output: "This is a fruit."
"apple"
and "banana"
share the same code block.
switch
Instead of if...else
?โ Use switch
when checking multiple possible values of a variable.
โ It makes the code cleaner and more readable than multiple if...else
statements.
switch
checks for a match and executes the corresponding code.break
prevents execution from falling into the next case.default
executes if no match is found.
@asadmukhtar