The switch
statement in JavaScript is used to execute one block of code among multiple options. It simplifies the process of writing complex conditional logic using multiple if
statements.
Switch Statement in JavaScript
Basic Syntax of a Switch Statement
switch (expression) {
case value1:
// code block to execute
break;
case value2:
// code block to execute
break;
default:
// code block to execute if no cases match
}
In this syntax, the expression
is evaluated once, and its value is compared with each case
. If there is a match, the corresponding code block is executed.
Example of a Switch Statement
const day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
default:
dayName = "Invalid day";
}
console.log(dayName); // Output: Wednesday
In this example, the variable day
is matched against several cases, and the corresponding day name is assigned to dayName
.
Omitting Break Statements
If you omit the break
statement, the code will continue executing into the next case, which can be useful in certain situations:
const score = 85;
let grade;
switch (true) {
case score >= 90:
grade = "A";
break;
case score >= 80:
grade = "B";
case score >= 70:
grade = "C";
break;
default:
grade = "F";
}
console.log(grade); // Output: B
In this example, since there is no break
after case 80, both cases for 'B' and 'C' are executed if the score is 80 or higher.
Default Case
The default
case is executed if none of the specified cases match the expression:
const fruit = "banana";
switch (fruit) {
case "apple":
console.log("Apple pie!");
break;
case "banana":
console.log("Banana smoothie!");
break;
default:
console.log("Fruit not found.");
}
If the fruit
variable matches "banana", the output will be "Banana smoothie!"
Conclusion
The switch
statement is a useful alternative to multiple if
statements, making code cleaner and easier to read when dealing with multiple conditions. However, it's important to remember to include break
statements to avoid unintentional fall-through behavior.