JavaScript
Coding
Switch Statement
Programming
Web Development

Switch statement for multiple cases in JavaScript

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

A switch statement in JavaScript evaluates an expression and matches the expression’s value to a case clause, executing statements associated with that case. It’s often used as an alternative to a long series of if-else-if statements and can make the code more readable and efficient when dealing with multiple conditions.

Basics of Switch Statement

A switch statement tests a value against multiple possible matches, which can lead to various actions. The basic syntax of a switch statement in JavaScript is shown below:

javascript
1switch(expression) {
2  case value1:
3    // Statements executed when the result of expression matches value1
4    break;
5  case value2:
6    // Statements executed when the result of expression matches value2
7    break;
8  default:
9    // Statements executed if none of the cases match
10}

Here, the expression is evaluated once and compared with values in the case clauses. If a match is found, JavaScript executes the statements in that case clause until it encounters a break statement, which exits the switch statement. If no case matches, the default clause is executed, if it exists.

Grouping Multiple Cases

You might encounter scenarios where multiple cases should execute the same code. In such instances, multiple case clauses can be combined or grouped together, leading to cleaner and more efficient code. Here's an example of grouping multiple case clauses:

javascript
1switch(day) {
2  case 'Monday':
3  case 'Tuesday':
4  case 'Wednesday':
5  case 'Thursday':
6  case 'Friday':
7    console.log('Weekday');
8    break;
9  case 'Saturday':
10  case 'Sunday':
11    console.log('Weekend');
12    break;
13  default:
14    console.log('Invalid day');
15}

In this example, if the value of day matches any of the weekdays, JavaScript will log "Weekday." It won’t check subsequent cases once a match is found unless omitted break leads to a fall-through.

Fall-through Behavior

One important feature in switch cases is the "fall-through" behavior. Without a break statement, a case will run into the next until a break is encountered. Here’s an example:

javascript
1switch(fruit) {
2  case 'Apple':
3    console.log('Apple is $1');
4    // fall-through
5  case 'Banana':
6    console.log('Banana is $2');
7    break;
8  default:
9    console.log('Unknown fruit');
10}

In the above, if fruit is 'Apple', it logs "Apple is 1",andthencontinuestotheBananacaselogging"Bananais1", and then continues to the 'Banana' case logging "Banana is2". It is a powerful feature but should be handled with care to avoid unwanted behavior.

Use Cases and Practical Applications

The switch statement is useful for scenarios where one variable might equal multiple possible values that a user might input. Common use cases include:

  • Command parsers (e.g., different commands input into a console application)
  • UI button identifiers (determining what action to take based on which button is pressed)
  • State machines (different states leading to different actions)

Summary Table

FeatureDescription
EvaluationExpression evaluated once and matched against case values.
Case groupingMultiple cases can execute the same piece of code.
Break & fall-throughbreak stops the execution of cases; omission causes fall-through.
Use casesHandling multiple conditional paths clearly and efficiently.

Overall Recommendations

When using a switch statement, remember:

  • Always consider adding a break statement unless intentional fall-through is needed.
  • For improved readability, logically group cases whenever practical.
  • Use the default case to handle unexpected or invalid cases.

Conclusion

switch statements in JavaScript are a robust alternative to multiple if...else statements. They provide a clear way to handle multiple conditions that depend on the same variable, improving both readability and maintainability of the code.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.