The Wayback Machine - https://web.archive.org/web/20240920014713/https://www.geeksforgeeks.org/switch-case-in-javascript/
Open In App

JavaScript switch Statement

Last Updated : 22 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The JavaScript switch statement evaluates an expression and executes a block of code based on matching cases. It provides an alternative to long if-else chains, improving readability and maintainability, especially when handling multiple conditional branches.

Switch Statement Syntax

switch (expression) {
case value1:
// code block 1;
break;
case value2:
// code block 2;
break;
...
default:
// default code block;
}
  • Expression is the value that you want to compare.
  • Case value1, case value2, etc., represent the possible values of the expression.
  • break statement terminates the switch statement. Without it, execution will continue into the next case.
  • Default specifies the code to run if none of the cases match the expression.

How Switch Statement Works

  • Evaluation: The expression inside the switch the statement is evaluated once.
  • Comparison: The value of the expression is compared with each case label (using strict equality ===).
  • Execution: If a match is found, the corresponding code block following the matching case the label is executed. If no match is found, the execution jumps to the default case (if present) or continues with the next statement after the switch block.
  • Break Statement: After executing a code block, the break statement terminates the switch statement, preventing execution from falling through to subsequent cases. If break is omitted, execution will continue to the next case (known as “fall-through”).
  • Default Case: The default case is optional. If no match is found, the code block under default is executed.

Flowchart of Switch Statement

Switch Statement Example:

Here, we will print the day name on day 3.

JavaScript
let day = 3;
let dayName;

switch (day) {
    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;
    case 7:
        dayName = "Sunday";
        break;
    default:
        dayName = "Invalid day";
}

console.log(dayName); // Output: Wednesday

Output
Wednesday

Explanation:

  • Day is set to 3.
  • The switch statement evaluates day.
  • Since day is 3, the case 3 the block is executed, assigning "Wednesday" to dayName.
  • The break statement ends the switch statement, preventing execution from continuing into other cases.

Switch Statement Example:

Here, 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)

Explanation:

  • Grade is assigned the value 'B'.
  • The switch statement evaluates the value of grade.
  • Since grade is 'B', the code block following case 'B': is executed.
  • The result the variable is assigned the string "B (Average)".
  • The break statement terminates the switch statement.
  • result is logged to the console, which outputs "B (Average)".

Break Keyword

The break the keyword is used to terminate the execution of a loop or a switch statement.

default Keyword

The default the keyword is used within a switch statement as a fallback option when none of the case expressions match the value being evaluated. It acts similarly to the else statement in an if...else chain, providing a default action to take when no other specific cases match.

Position of default case does not matter:

Regardless of its placement, the default case only gets executed if none of the other case conditions are met. So, putting it at the beginning, middle, or end doesn’t change the core logic (unless you’re using a less common technique called fall-through).

we will print the default case.

JavaScript
let day = 8;
let dayName;

switch (day) {
    default:
        dayName = "Invalid day";
        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;
    case 7:
        dayName = "Sunday";
        break;
    
}

console.log(dayName);

Output
Invalid day

Common Code Blocks

In some cases, we need to use the same code for multiple switch cases. Let’s see an example of how to do it:

Common Code Blocks Example:

Here, we will same code blocks for two different switch cases.

JavaScript
let grade = 'A'
let result;

switch (grade) {
    case 'A':
        result = "Grade is excellent"
        break;
    case 'B':
        result = "Grade is good"
        break;
    case 'C':
        result = "Grade is Average "
        break;
    case 'D':
        result = "Grade is Poor"
        break;
    default:
        text = "NO grades achieved";
}
console.log(result)

Output
Grade is excellent

Explanation:

  • Grade is assigned the value 'A'.
  • The switch statement evaluates the value of grade.
  • Since grade matches 'A', the code block following case 'A': is executed, setting result to "Grade is excellent".
  • The break statement terminates the switch statement.
  • Result is logged to the console, which outputs "Grade is excellent".

Note: If multiple switch cases match a value, the first is executed.

JavaScript switch Statement-FAQs

Why do we use the break statement in a switch block?

The break statement is used to terminate the switch block once a matching case is executed. Without break, the code will continue executing the subsequent cases (known as “fall-through”), even if they don’t match.

What happens if there is no matching case in a switch statement?

If no cases match, the default block (if provided) will be executed. If there’s no default block, no code runs if there are no matches.

Can I use a switch statement with non-integer values like strings or objects?

Yes, the switch statement can handle strings, booleans, and other data types, but it compares using strict equality (===), meaning the types must match exactly.

How is the switch statement different from if-else statements?

The switch statement is often more readable and organized when dealing with multiple conditions based on a single expression, while if-else is better for more complex or range-based conditions.

Can a switch statement handle range conditions (e.g., x > 10)?

No, the switch statement is designed for exact matches. For range conditions, use if-else statements or include logical expressions within the cases.



Previous Article
Next Article

Similar Reads

How to optimize the switch statement in JavaScript ?
The switch statement is necessary for certain programming tasks and the functionality of the switch statement is the same among all programming languages. Basically switch statements switch the cases as per the desired condition given to the switch. A switch statement can be used when multiple numbers of consecutive if/else statement is in use. But
2 min read
How to write a switch statement in JavaScript?
In JavaScript, a switch statement is a control flow statement that evaluates an expression and executes code based on matching cases. It provides a more concise and readable way to handle multiple possible conditions compared to nested if...else statements. Syntax:switch (expression) { case value1: // code block to be executed if expression matches
2 min read
PHP switch Statement
The switch statement is similar to the series of if-else statements. The switch statement performs in various cases i.e. it has various cases to which it matches the condition and appropriately executes a particular case block. It first evaluates an expression and then compares it with the values of each case. If a case matches then the same case i
2 min read
How to switch between multiple CSS stylesheets using JavaScript ?
Many websites on the internet are available in multiple themes. One can obtain any feature by making multiple stylesheets into the HTML code and enabling one at a time. A CSS file is included into the HTML in the <head> tag using the <link> tag. <link id="theme" rel="stylesheet" type="text/css" href="light.css" /> The "href" attri
2 min read
How to add bootstrap toggle-switch using JavaScript ?
Bootstrap toggle-switch is a simple component used for activating one of the two given options. Commonly used as an on/off button. The CSS framework is a library that allows for easier, more standards-compliant web design using the Cascading Style Sheets language. Bootstrap 4 is one such widely used CSS framework used by web developers for building
2 min read
How to Redeclare a Variable Inside a Switch Block in JavaScript ?
Generally, in JavaScript, if you try to declare a variable with the same name inside a switch block will throw a syntaxError for declaring the variable again in the same block using the let keyword. We can overcome this problem by enclosing the code for every case statement inside a block using the curly brackets({}) and then redeclare the variable
1 min read
JavaScript Program for Pattern Matching for Switch
In this article, we will learn about Pattern Matching for Switch using Javascript, Pattern matching is a programming language feature that allows you to match values against patterns and execute corresponding blocks of code. While JavaScript has traditionally used the switch statement for conditional branching modern proposals are introducing a mor
2 min read
How to switch the language of the page using JavaScript ?
In this article, we will describe the method to switch between languages of a page depending upon the choice of the user. The method works by using the hash fragment of the URL as an identifier that can be used later detected by the script to change the language. The hash is accessed using window.location.hash property in JavaScript and can be late
3 min read
How to write an inline IF statement in JavaScript ?
We can write an inline IF statement in javascript using the methods described below. Method 1: In this method we write an inline IF statement Without else, only by using the statement given below. Syntax: (a < b) && (your code here) Above statement is equivalent to if(a < b){ // Your code here } Example: Below is the implementation of
2 min read
JavaScript SyntaxError - Missing ; before statement
This JavaScript exception missing ; before statement occurs if there is a semicolon (;) missing in the script. Message: SyntaxError: Expected ';' (Edge) SyntaxError: missing ; before statement (Firefox) Error Type: SyntaxError Cause of Error: Somewhere in the code, there is a missing semicolon (;). You need to provide it so that JavaScript can pars
1 min read
JavaScript SyntaxError - Function statement requires a name
This JavaScript exception function statement requires a name that occurs if there is any function statement in the script which requires a name. Message: Syntax Error: Expected identifier (Edge) SyntaxError: function statement requires a name [Firefox] SyntaxError: Unexpected token ( [Chrome] Error Type: Syntax Error Cause of Error: Any function st
1 min read
What does OR Operator || in a Statement in JavaScript ?
JavaScript is a dynamic programming language that allows developers to write complex code with ease. One of the fundamental concepts in JavaScript is the use of operators, which are symbols that perform operations on one or more values. One such operator is the || (logical OR) operator, which can be used in a variety of ways to simplify code and ma
6 min read
JavaScript Continue Statement
The continue statement in Javascript is used to break the iteration of the loop and follow with the next iteration. The break in the iteration is possible only when the specified condition going to occur. The major difference between the continue and break statement is that the break statement breaks out of the loop completely while continue is use
2 min read
How do you Make an If Statement in JavaScript that Checks if a Variable is Equal to a Certain Word ?
In this article, we will discuss How You Make An If Statement In JavaScript That Checks If A Variable is Equal To A Certain Word. In JavaScript, an if statement is a basic control structure that allows you to conditionally execute code based on specified conditions. A common use case is to check if the value of the variable is equal to a specific w
2 min read
How to use multiple ternary operators in a single statement in JavaScript ?
In this article, we will see how we can use multiple ternary operators in a single statement in JavaScript. Sometimes using conditional statements like if, else, and else if stretches the code unnecessarily and makes the code even more lengthy. One trick to avoid them can be the use of ternary operators. But what if we are to use multiple if-else s
2 min read
JavaScript Break Statement
JavaScript break statement is used to terminate the execution of the loop or the switch statement when the condition is true. In a switch, code breaks out and the execution of code is stopped. In a loop, it breaks out to the loop but the code after the loop is executed.Syntax:break;Using LabelsA label reference can be used by the break statement to
2 min read
Explain the differences between for (..in) and for (..of) statement in JavaScript
Often in a JavaScript script, we iterate over some objects of a few built-in classes like Arrays, Dictionaries, Strings, Maps, etc. We iterate the objects using loops. JavaScript supports different kinds of loops: for loopfor (..in) loopfor (..of) loopwhile loopdo-while loopIn this article, we will be learning about the difference between these two
2 min read
JavaScript with Statement
The with statement in JavaScript allows for simplified access to object properties by establishing a default object scope. While it can reduce code repetition, it is generally discouraged due to potential confusion and negative impacts on code maintainability and performance. Syntax:with (object) { // Statement(s) that access properties of `object`
2 min read
What is the use of the Break Statement in a Loop in JavaScript ?
The break statement in JavaScript is used to prematurely terminate a loop, allowing the program to exit the loop before the normal loop condition is met. It is often used to interrupt the loop execution based on certain conditions. Example: Here, the while loop will continue indefinitely (since the condition is true). However, the if statement insi
1 min read
JavaScript Label Statement
JavaScript label statement is used to label a block of code. A labeled statement can be used with loops and control flow statements to provide a target for the break and continue statements. Syntax: Label: statement (loop or block of code)Keywords to be used:Label: A unique string that is Used to define the name of the block or loop.Statement: It c
3 min read
How to use if statement in JavaScript ?
An if statement in JavaScript is used for conditional execution. It evaluates a condition inside parentheses and executes a block of code if the condition is true. The if statement is one of the fundamental building blocks in programming, enabling developers to create dynamic and responsive applications. By using if statements, you can control the
1 min read
How to Break Statement in an Array Map Method in JavaScript?
Map method in JavaScript is used to create a new array populated with the results of calling a provided function on every element in the calling array. But Unlike loops, the map method cannot be broken once started, and it always iterates through the entire array. Using these approaches we will be break statements in an array map method in JavaScri
2 min read
JavaScript return Statement
The JavaScript return statement is used to stop the function's execution and optionally return a value to the caller. When a return statement is encountered, the function stops running and outputs the specified value, allowing the function to pass data back. It can be used to return a specific value, variable, or expression to the caller. If no val
3 min read
How to use a switch case 'or' in PHP?
Problem: How to use a switch case 'or' in PHP? Solution: This can be achieved in 2 ways. They are as follows: Method 1: Without using break keyword in one of the switch case. Example: <?php $option = 1; switch ($option) { case 1: case 2: echo "The option is either 1 or 2."; break; } ?> Output: The option is either 1 or 2. Method 2:
1 min read
AngularJS ng-switch Directive
The ng-switch Directive in AngularJS is used to specify the condition to show/hide the child elements in HTML DOM. The HTML element will be displayed only if the expression inside the ng-switch directive returns true otherwise it will be hidden. It is supported by all HTML elements. Syntax: <element ng-switch="expression"> <element ng-swit
2 min read
How to create Disable flip toggle switch using jQuery Mobile ?
jQuery Mobile is a web based technology used to make responsive content that can be accessed on all smartphones, tablets and desktops. In this article, we will be making Disable flip toggle switch using jQuery Mobile. Approach: First, add jQuery Mobile scripts needed for your project. <link rel="stylesheet" href="http://code.jquery.com/mobile/1.
1 min read
SVG <switch> Element
The <switch> SVG element is used to evaluate attributes on its direct child elements in order and then renders the first child where these attributes evaluate to true. Other remaining children will not be rendered. Syntax: <switch attribute="" > <child 1> <child 2> <child 3> <child n> </switch> Attributes:
1 min read
How to change the “checked” background color of toggle switch in Bootstrap 4?
Bootstrap is a popular choice among web developers for building interactive webpage designs. Bootstrap has come along a long way with multiple releases and enriched content with every new release. Bootstrap has a wide community that has also contributed newer packages that have made working with Bootstrap easier. In this article, we shall deal with
4 min read
How to create a Label hidden flip toggle switch using jQuery Mobile ?
jQuery Mobile is a web-based technology used to make responsive content that can be accessed on all smartphones, tablets, and desktops. In this article, we will be making label hidden flip toggle switch using jQuery Mobile. Approach: First, add jQuery Mobile scripts needed for your project. <link rel="stylesheet" href="http://code.jquery.com/mob
1 min read
How to create Mini flip toggle switch using jQuery Mobile ?
jQuery Mobile is a web-based technology used to make responsive content that can be accessed on all smartphones, tablets, and desktops. In this article, we will be making a Mini flip toggle switch using jQuery Mobile. Approach: First, add jQuery Mobile scripts needed for your project. <link rel="stylesheet" href="http://code.jquery.com/mobile/1.
1 min read