On this page
switch in JavaScript
The switch
statement in JavaScript is used to perform different actions based on different conditions. It’s an alternative to using multiple if-else if
statements and can make your code easier to read and manage when you have a large number of conditions.
Syntax
switch(expression) {
case value1:
// Code to execute if expression === value1
break;
case value2:
// Code to execute if expression === value2
break;
// Add more cases as needed
default:
// Code to execute if none of the cases match
}
Key Points
- The
expression
is evaluated once and compared with the values of eachcase
. - If a match is found, the corresponding block of code is executed.
- The
break
statement is used to exit theswitch
block once a matching case is executed. Withoutbreak
, the code will continue to execute the subsequent cases (fall-through behavior). - The default case is optional and executes if none of the cases match the expression.
Example
let day = 3;
let dayName;
switch(day) {
case 0:
dayName = "Sunday";
break;
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;
default:
dayName = "Invalid day";
}
console.log(dayName); // Outputs: Wednesday
In this example, the value of day
is 3
, so the case 3
block is executed, setting dayName
to “Wednesday”.
Example with Fall-through Behavior
let fruit = "apple";
let color;
switch(fruit) {
case "banana":
case "lemon":
color = "yellow";
break;
case "apple":
case "cherry":
color = "red";
break;
case "orange":
color = "orange";
break;
default:
color = "unknown";
}
console.log(color); // Outputs: red
In this example, both “apple” and “cherry” result in color
being set to “red” due to the fall-through behavior when cases are grouped without a break
statement between them.
Example with default
Case
let score = 95;
let grade;
switch (true) {
case (score >= 90):
grade = 'A';
break;
case (score >= 80):
grade = 'B';
break;
case (score >= 70):
grade = 'C';
break;
case (score >= 60):
grade = 'D';
break;
default:
grade = 'F';
}
console.log(grade); // Outputs: A
In this example, the switch
statement uses true
as the expression to match ranges of scores to grades. The default
case assigns ‘F’ if none of the other conditions are met.