JavaScript switch case

The working functionality of the JavaScript switch statement is almost the same as multiple if conditions. A switch statement contains an expression and may have n number of cases.

The switch statement evaluates the expression and compares the expression value with the values assigned in the case statements. If both the values (expression and case value) match, then the code block present in that case statement will execute until the compiler encounters the break statement.

NOTE: The JavaScript switch statement is the best alternative to the else if and nested if statements. When the number of conditions increases, both of them are difficult to understand. However, the switch case is easy to understand.

JavaScript switch case syntax

The syntax of the switch statement is as follows:

switch(expression) 
{
case Option 1:
//Execute these when the expression result matches Option 1
break;
case Option 2:
//Execute these when the expression result matches Option 2
break;
case Option 3:
//Execute these when the expression result matches Option 3
break;
...
case Option N:
//Execute when the result of the expression matches Option N
break;
default:
//Execute when the result of the expression does not match any Option
break;
}

TAs you can see from the syntax, the switch statement has an expression followed by curly braces. Inside {}, there are case labels with options and an optional default case statement.

How does JavaScript switch case work?

The switch statement evaluates the expression and compares the result with the case labels. If true, execute code in the case block and run break to exit the switch case. If no matching is found, the default case clause will execute. There are four important components in the switch case. They are

  • Expression: The JavaScript switch case expression should be either an integer or characters (we can write the expression as n/2…. also, but the result should be an integer). The expression result is matched against each case clause.
  • case clause: The case clause is used to match Option (1 to N) against an expression. Option 1 and Option 2…… are constants. It will only accept integers or characters. If the expression matched with the Option, the code inside that case block will start executing. It continues the execution until it reaches the break statement.
  • Default case: The JavaScript switch case allows us to add a default case. If the expression value does not match any of the case blocks, then the code present in the default block will be executed.
  • Break: The Break statement is useful to come out of the switch statement. Otherwise, all the statements in the switch condition will execute. Whenever a break is encountered, the execution flow would directly come out of the case clause.

JavaScript switch case example

This program allows us to use Arithmetic Operators to perform arithmetic operations using Switch Case. Please refer to Else If, Nested If, and Break statement articles in JavaScript.

let operator = '+';
let number1 = 10, number2 = 2;
switch (operator) {
case '+':
console.log('Addition of two numbers is: ' + (number1 + number2));
break;
case '-':
console.log('Subtraction of two numbers is: ' + (number1 - number2));
break;
case '*':
console.log('Multiplication of two numbers is: ' + number1 * number2);
break;
case '/':
console.log('Division of two numbers is: ' + number1 / number2);
break;
case '%':
console.log('Module of two numbers is: ' + (number1 % number2));
break;
default:
console.log('<b> You have entered Wrong operator </b>');
console.log(
'<br \> Please enter Correct operator such as +, -, *, /, %',
);
}

OUTPUT 1: Here, we assigned * as the operator variable.

Multiplication of two numbers is: 20

Output 2: To check the default value, we change the operator from valid to the wrong operator (var operator = ‘//’;).

You have entered Wrong operator
Please enter Correct operator such as +, -, *, /, %

Importance of a break in a JavaScript switch statement

Whether it is a loop iteration or a switch case, the break statement terminates execution, and control will jump out of the loop or switch statement.

If you observe the program below, we set the day as Monday. So, when the compiler enters the switch case, the expression matches the first case option. So, it should return ‘Start of the week!’ as the output. However, the output shows all the messages.

let day = 'Monday';

switch (day) {
case 'Monday':
console.log('Start of the week!');
case 'Tuesday':
console.log('Its a Tuesday!');
case 'Wednesday':
console.log('Middle of the Week!');
default:
console.log('Invalid day.');
}
Start of the week!
Its a Tuesday!
Middle of the Week!
Invalid day.

Since there are no break statements, the control will not jump out of the switch statements. Instead, it executes all the existing statements.

let day = 'Wednesday';

switch (day) {
case 'Monday':
console.log('Start of the week!');
break;
case 'Tuesday':
console.log('Its a Tuesday!');
break;
case 'Wednesday':
console.log('Middle of the Week!');
break;
default:
console.log('Invalid day.');
}
Middle of the Week!

Switch case with the Default keyword

The default keyword is a fallback option to the JavaScript switch statement when the existing case labels fail. The switch statement checks the expression against the options in the case labels.

If there is a matching case option, it will execute. However, if there are no case matches, we must ensure something returns. In such a case, we can use the default block that will execute when there is no matching case.

NOTE: It is entirely optional to use the default case. Something like if else.

The following program returns nothing as output because the given day is Wednesday, and there is no matching case in the switch statement.

let day = 'Wednesday';

switch (day) {
case 'Monday':
console.log('Start of the week!');
break;
case 'Friday':
console.log('Its Weekend!');
break;
}

However, if we use the default block, we can inform the user about something.

let day = 'Wednesday';

switch (day) {
case 'Monday':
console.log('Start of the week!');
break;
case 'Friday':
console.log('Its Weekend!');
break;
default:
console.log('Middle of the Week!');
break;
}
Middle of the Week!

FAQs

JavaScript switch case multiple values

There are situations where we have to run the same code multiple case options. In such a situation, we follow the technique below.

let grade = 'A';
let result;

switch (grade) {
case 'A':
case 'B':
result = 'Your Performance is Good';
break;
case 'C':
case 'D':
result = 'Your Performance is OK';
break;
default:
result = 'No grades achieved. Bad Performance';
}
No grades achieved. Bad Performance

NOTE: Please change the grade value at the top (first line) to other grades to see different messages.

JavaScript switch case multiple conditions

We can use the combination of a switch case and logical operators (AND and OR) to check multiple conditions. To do so, we must set the switch expression to true and use the logical AND or logical OR operator to separate multiple conditions.

The following program checks whether the user is eligible to vote in the elections. The case label verifies whether the user is 18 years of age or older and possesses a valid voter ID.

const age = 27;
const hasVoterID = true;

switch (true) {
case age >= 18 && hasVoterID:
console.log("Person can Vote");
break;

case age >= 18 && !hasVoterID:
console.log("Apply For the Voter ID");
break;

case age < 18:
console.log("Not eligible to Vote");
break;

default:
console.log("Records Missing...");
}
Person can Vote

JavaScript switch case greater than

Similar to the else if conditions, we cannot use the condition on the case label. Using the comparison operator directly on the case label is incorrect. For instance, a case greater than 70 (case > 70) is incorrect syntax.

To utilize the greater than, less than, equal to, or any conditional check, we must use the switch case with always true expressions (switch(true)). In the following program, we used only two conditions. However, we can use more conditions with different comparison operators.

const marks = 80;

switch (true)
{
case marks >= 85:
console.log("Grade A");
break;

case marks >= 70:
console.log("Grade B");
break;
default:
console.log("Grade C");
}
Grade B

Difference between if else and switch statement

  • if else: It is useful for complex conditions. Use when the result is True or False.
  • switch case: It is useful for exact matches. Use when there are multiple values to check against the expression result.