Switch Statement
JavaScript Switch Statement
The switch
statement in JavaScript provides a way to perform different actions based on the value of an expression. It is often used as an alternative to a series of if-else
statements when there are multiple possible matches for a given value. The basic syntax of a switch
statement looks like this:
let expression = value;
switch (expression) {
case value1:
// Code to be executed if expression === value1
break;
case value2:
// Code to be executed if expression === value2
break;
// Additional cases...
default:
// Code to be executed if none of the cases match
}
Example:
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
console.log(dayName); // Outputs: "Wednesday"
In this example:
- The
switch
statement evaluates the value of theday
variable. - Each
case
represents a possible value ofday
. - If a match is found, the corresponding block of code is executed until the
break
statement is encountered. - If no match is found, the code inside the
default
block is executed.
Note that the break
statement is crucial to exit the switch
block once a matching case is found. If you omit the break
, the execution will "fall through" to the next case, and so on.
Switch statements are particularly useful when you have a value that may have multiple possible matches and you want to avoid a series of if-else
statements.