GeeksforGeeks App
Open App
Browser
Continue

Switch Case in JavaScript

We have learned about decision-making in JavaScript using if-else statements in our previous article on if-else statements in JavaScript. We have seen in our previous article that we can use the if-else statements to perform actions based on some particular condition. That is if a condition is true then perform some task or else if the condition is false then execute some other task.

The switch case statement in JavaScript is also used for decision-making purposes. In some cases, using the switch case statement is seen to be more convenient than if-else statements. Consider a situation when we want to test a variable for hundred different values and based on the test we want to execute some task. Using if-else statements for this purpose will be less efficient than switch-case statements and also it will make the code look messy.

The switch statement analyses an expression, compares the outcome to the case value, and then executes the statement that corresponds to the correct case value.

Syntax

```switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}```

Explanation:

• The expression can be of type numbers or strings.
• Duplicate case values are not allowed.
• The default statement is optional. If the expression passed to the switch does not match the value in any case then the statement under default will be executed.
• The break statement is used inside the switch to terminate a statement sequence.
• The break statement is optional. If omitted, execution will continue on into the next case.
• Cases are compared strictly.

Flowchart

Example 1: In this example, we will check our I value with help of a switch case.

JavaScript

 `// JavaScript program to illustrate switch-case``let i = 9;` `switch` `(i) {``    ``case` `0:``        ``console.log(``"i is zero."``);``        ``break``;``    ``case` `1:``        ``console.log(``"i is one."``);``        ``break``;``    ``case` `2:``        ``console.log(``"i is two."``);``        ``break``;``    ``default``:``        ``console.log(``"i is greater than 2."``);``}`

Output:

`i is greater than 2.`

Example 2: In this example, we will check our grade by using a switch case.

Javascript

 `let grade = ``'B'``;``let result;``switch` `(grade) {``    ``case` `'A'``:``        ``result = ``"A (Excellent)"``;``        ``break``;``    ``case` `'B'``:``        ``result = ``"B (Average)"``;``        ``break``;``    ``case` `'C'``:``        ``result = ``"C (Below than average)"``;``        ``break``;``    ``default``:``        ``result = ``"No Grade"``;``}``console.log(result);`

Output:

`B (Average)`

My Personal Notes arrow_drop_up
Related Tutorials