Switch Case
The "switch" statement in JavaScript is used to execute a block of code based on the value of a variable or expression.
The switch statement is a control structure in JavaScript that allows you to execute a block of code based on the value of a variable or expression. It is called a switch statement because it switches between different cases based on the value of the variable or expression.
Syntax
Here is the syntax for a switch statement in JavaScript:
switch (expression) {
case value1:
// code to be executed if expression is equal to value1
break;
case value2:
// code to be executed if expression is equal to value2
break;
// more cases...
default:
// code to be executed if none of the cases are true
}The expression is evaluated, and the code in the corresponding case block is executed if the value of the expression matches the value specified in the case. If none of the cases match, the code in the default block is executed.
Each case block is followed by an optional break statement. The break statement is used to exit the switch statement and prevent the execution of subsequent case blocks. If the break statement is omitted, the code will continue to execute the next case block until a break statement is encountered.
Examples
Here are some examples of using a switch statement in JavaScript:
let 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;
case 5:
console.log("Friday");
break;
default:
console.log("Weekend");
}In this example, the value of day is 3, so the code in the case 3 block is executed, and the output is:
WednesdayHere is another example:
let color = "red";
switch (color) {
case "red":
console.log("Red color");
break;
case "blue":
console.log("Blue color");
break;
case "green":
console.log("Green color");
break;
default:
console.log("Unknown color");
}In this example, the value of color is "red", so the code in the case "red" block is executed, and the output is:
Red colorConclusion
- The
switchstatement in JavaScript is used to execute a block of code based on the value of a variable or expression. - The
switchstatement is an alternative to using multipleif-elsestatements when you have multiple conditions to check. - Each
caseblock is followed by an optionalbreakstatement to prevent the execution of subsequentcaseblocks. - The
defaultblock is executed if none of thecaseblocks match the value of theexpression.
How is this guide?
Sign in to share your feedback
Help us improve by sharing your thoughts on this guide.
Last updated on