Last Updated:

Switch statement in JavaScript | Examples

The structure of the switch statement is as follows:

switch(variable_to_test){case value: code_here;break;case value: code_here;break;default: values_not_caught_above;}

So you start with the word switch, followed by a pair of parentheses. The variable you want to check is in the parentheses switch. Then there are the curly braces. They contain all the other parts of the switch statement.

 

For each value you want to check, you need the word case. Then write the value itself, which you want to check:

This is followed by a colon. Next, you put the code you want to execute if the value matches.

 

The break keyword is required to exit each case switch statement.

The default value at the end is optional. It can be enabled if there are other values that can be stored in your variable, but which you have not checked in your case in switch.

 

If all this is confusing, try the following code.

 

You can start a new project or simply comment out the code you have. A quick way to comment out code in NetBeans is at the top of the toolbar. First, select the code you want to comment out. Then click the comment icon:

If you don't have this toolbar, then click View at the top, and choose the Show Editor Toolbar from the drop-down list:

So, the code:

publicstaticvoid main(String[] args){int user =21;switch(user){case18:System.out.println("You are 18 years old");break;case19:System.out.println("You are 19 years old");break;case20:System.out.println("You are 20 years old");break;default:System.out.println("You are not 18, 19 or 20 years old");}}

The first thing the code does is set the value to validate. Again, we created an int variable and named it user, setting it to 18.

The switch statement will check our variable and see what's in it.

It will then go through each of the cases in turn. When it finds one that matches, it stops and executes the code for that case.

Then the switch statement exits.

Run this program. Enter different values for the user variable and see what happens.

Unfortunately, we can't check the range of values, just one. So we can't do this:

case (user <= 18):

But we can do this:

case1:case2:case3:case4:

The above line checks the range of values from 1 to 4. But you have to spell out each value. (Note where all the cases and colons are.)

To finish this section about conditional statements, try these exercises.

An exercise C

Write a program that accepts user input from the console. The program must take a number and then be tested for the following age ranges: 0 to 10, 11 to 20, 21 to 30, 31 and older. Display the message in the Output window in the following format:

age +" it's between 21 and 30 years old"

That is, if the user enters his age of 27 years, the output window should look like this:

If the user is 30 or older, you can simply display the following message:

"You are over 30 years old"

Response to Exercise C

Help for this exercise

To get String values from a user, you must do this:

String age = user_input.next();

But the next() method is used for strings. The age you get from a user must be an integer, so you can't use next(). However, there is a similar method you can use: nextInt().

Use the switch statement.

An exercise D

 

If you want to check if one line is the same as another, you can use a method named equals.

String user_name ="John",if(user_name.equals){//some code}

 

In the code above, we created a String variable and named it user_name. Then we gave it the value "Ivan." In parentheses if, we again write the variable name followed by a period. The dot is followed by the word equals. Between another pair of parentheses, you enter the string you want to check.

NOTE. When checking whether one line matches another, note that they must match exactly. That is, "Ivan" is different from "Ivan". The first has a capital letter "I", and the second has a lowercase "and".
For this exercise, write a program in which the user is asked to choose one of four colors: black, white, red or blue. Use if... else if to display one of the following messages, depending on which color was selected:

BLACK "You must be a brunette!"
WHITE "You are a bright person"
RED "You are cheerful and sociable"
BLUE "You are a creative person"

Syntax Javascript Switch Case

 

Switch (expression) { Case Option 1: //Execute this statement when the result of the expression matches Option 1 break; Case Option 2: // Execute this statement when the result of the expression matches Option 2 break; Case Option 3: // Execute this statement when the result of the expression matches Option 3 break; ...... Case Option N: // Execute this statement when the result of the expression matches Option N break; Default: // Execute this statement when the result of an expression does not match any of the Option break expressions; }

The value of the expression must be either an integer or a character. The expression can be written as n/2.... But the result must be an integer. Option 1, Option 2... they're all constants.

JavaScript Case allows us to add a default statement. If the value of the variable does not match any of the expressions, the default code will be executed.

The break statement is used to end the switch loop, otherwise all statements in the conditional switch expression will be executed. Each time a break is encountered, the execution thread is terminated.

 

Note: Switch Case in Javascript accepts only integers or characters, while the else if statement also accepts decimal fractions.

Principle of operation

How to add an element to a JS array or work with arrays in JavaScript as a pro

We present to your attention a special schedule that will help you understand the principle of operation

Example

This JavaScript switch case usage example allows us to perform arithmetic operations on numbers.

Javascript code

JavaScript Switch Case

Result 1: Here we entered * as an operator variable:

Result 2: Let's replace the current statement with an incorrect one to recheck the default value:

This publication is a translation of the article "JavaScript Switch Case", prepared by the editorial board of the project.

Switch statement in JavaScript

As you can imagine, using multiple if-else statements in the way shown above is inconvenient, to say the least. Therefore, almost all programming languages have a so-called selection operator.

The switch statement (sometimes called the "switch statement") selects a particular piece of code to execute, depending on the value of the variable being checked.

The same code we painfully wrote above, using the choice operator, would look like this:

 
var x = 1; switch(x) { case 1 : document.write(x = 1 <br>"); <p="" }="" default="" 3="" <br>");="" document.write("x="2" :="" 2="" case="" break;="" _istranslated="1">The switch(x) operator checks the value of the variable x, and compares it with the values specified after the words case. If it finds a match, it executes the source code that comes after the case. If no matches are found, the default code that follows the default word is executed.</br>");>

The word default is optional. If there is none, then in the absence of coincidences, simply nothing happens, and the script runs on.

 

IMPORTANTLY!

Pay attention to the break keyword. If you do not use it, then after the first match is found, all subsequent instructions will be executed, not just the block where the match was found. For example, here's the scenario:

 

var x = 2; //Use switch without break switch(x) { case 1 : document.write("x = 1 <br>"); <p="" }="" default="" 3="" <br>") ;="" document.write("x="2" :="" 2="" case="">will display:</br>");>

x = 2x = 3x = 2

NOTE
As someone who started learning programming with Pascal, this behavior of the choice operator has always been very infuriating to me. But JavaScript is based on C/C++, so it absorbed almost all their troubles.

Using switch in functions

As I said above, the break keyword should be used at the end of each case block. This word is used in this case to exit the switch block, that is, to complete the work of the selection operator.

If you use switch in the function, then you can not use the word break, but only use the return statement. Example:

function TestSwitch(op, x, y) 
{
switch(op)
{
case ‘+’ : return(x + y); case ‘-‘ : return(x - y); case ‘*’ : return(x * y); default : return("Unknown operation");
}
} document.write(TestSwitch('+', 1, 2));

This example will display the number 3.

As you can see, the JavaScript language is quite flexible. The same function can return both a numeric value and a string value, depending on the result. This, of course, is very convenient, although it can lead to errors due to the inattention of the programmer.

NOTE
The word default in our examples is specified at the end of the switch block. This corresponds to logic, but it does not have to be done this way, because the default in JavaScript can be placed anywhere in the switch block.

Break Statement

Although most switch statements in real life imply that only one of the case blocks must be executed, a break statement is required to exit the switch after the block is completed.

To demonstrate this, omit the break statements and add output to the console for each block:

public String forgetBreakInSwitch(String animal) { switch (animal) { case «DOG»: System.out.println(«domestic animal»); default: System.out.println(«unknown animal»); } }

Let's run this ForgotBreakInSwitch("DOG") code and check the output to make sure all the blocks are executed:

domestic animal
unknown animal

Therefore, we should be careful to add break statements at the end of each block unless we need to move to the code below the next label.

The only block that doesn't require a break is the last one, but adding a break to the last block makes the code less error-prone.

We can also use this behavior to drop a break when we want the same code to execute for multiple case statements. Let's rewrite the example from the previous section by grouping the first 2 cases:

public String exampleOfSwitch(String animal) { String result; switch (animal) { case «DOG»: case «CAT»: result = «domestic animal»; break; case «TIGER»: result = «wild animal»; break; default: result = «unknown animal»; break; } return result; }

Default keyword

The default keyword specifies the code to run if there are no case matches:

Example

The getDay() method returns the day of the week as a number between 0 and 6.

 

If today is neither Saturday (6) nor Sunday (0), write a default message:

switch (new Date().getDay()) {
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
break;
default:
text = "Looking forward to the weekend";
}

Common Code Blocks

Sometimes you may want different switching options to use the same code.

In this example, 4 and 5 share the same code block, and 0 and 6 share another code block:

Example

switch (new Date().getDay()) {
case 4:
case 5:
text = "Weekend is coming soon";
break;
case 0:
case 6:
text = "It's the weekend";
break;
default:
text = "Looking forward to the weekend";

Switching details

If multiple options match the case value, the first option is selected.

If no matching cases are found, the program goes to the default label.

If the default label is not found, the program proceeds to the statement(s) after the switch.

Strict comparison

In switching cases, a strict comparison (==== is used).

To match, the values must be of the same type.

A strict comparison can only be true if operands are of the same type.

Example

var x = "0";
switch (x) {
case 0:
text = "Off";
break;
case 1:
text = "On";
break;
default:
text = "Value not found";

Labels case

The first kind of label is case (or simply "case"), which is declared using the keywordcase and has a constant expression. A constant expression is one that generates a constant value, in other words: either a literal (for example, 5), or an enumeration (for example, COLOR_RED), or a constant (for example, a variable x that was declared with the const keyword).

The constant expression after the case keyword is checked for parity with the expression next to the switch keyword. If they match, then the code under the corresponding case is executed.

It is worth noting that all case expressions must produce unique values. That is, you will not be able to do the following:

<textarea wrap="soft" class="urvanov-syntax-highlighter-plain print-no" data-settings="" readonly="" style="-moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4; font-size: 13px !important; line-height: 20px !important;" > switch (z) { case 3: case 3: // not allowed, value 3 is already in use! case COLOR_PURPLE: // not allowed, COLOR_PURPLE evaluates to 3! };
123456switch(z){ case3: case3:// cannot, value 3 is already in use! caseCOLOR_PURPLE:// cannot, COLOR_PURPLE is calculated as 3!};

You can use several cases for one expression. The following function uses several cases to check whether the parameter p corresponds to the number from the ASCII table:

<textarea wrap="soft" class="urvanov-syntax-highlighter-plain print-no" data-settings="" readonly="" style="-moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4; font-size: 13px !important; line-height: 20px !important;" > bool isDigit(char p) { switch (p) { case '0': // if p = 0 case '1': // if p = 1 case '2': // if p = 2 case '3' : // if p = 3 case '4': // if p = 4 case '5': // if p = 5 case '6': // if p = 6 case '7': // if p = 7 case '8': // if p = 8 case '9': // if p = 9 return true; // return true default: // otherwise, return false return false; } }

 

12345678910111213141516171819
boolisDigit(charp)
{
Switch(p) if p = 3 case'4′:
// if p = 4 case'5′:
// if p = 5 case'6′:
// if p = 6 case'7′:
// if p = 7 case' 8′:
// if p = 8 case'9′:
// if p = 9 returntrue;
// return true default:
// otherwise return false returnfalse;
}

If p is a number from the ASCII table, then the first statement after the case will be executed - return true;.

Default label

The second type of label is a default label (called a "default case"), which is declared using the default keyword. The code under this label is executed if none of the cases match the switch expression. The default label is optional. There can be only one default in one switch. It is usually declared the most recent in the switch block.

In the above example, if p is not a number from the ASCII table, then the default label is executed and false is returned.

switch и fall-through

One of the trickiest things about switching is the sequence in which the code runs. When the case matches (or default is executed), execution begins with the first statement, which is located after the corresponding case and continues until one of the following completion conditions is met:

The end of the switch block has been reached.

The return statement is executed.

The goto statement is executed.

A break statement is executed.

Note that if none of these completion conditions occur, then all cases will be executed after the case that coincided with the switch expression. For example:

<textarea wrap="soft" class="urvanov-syntax-highlighter-plain print-no" data-settings="" readonly="" style="-moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4; font-size: 13px !important; line-height: 20px !important;" > switch (2) { case 1: // Doesn't match! std::cout << 1 << 'n'; // skip case 2: // Matched! std::cout << 2 << 'n'; // code execution starts here case 3: std::cout << 3 << 'n'; // this will also be executed case 4: std::cout << 4 << 'n'; // and this is default: std::cout << 5 << 'n'; // and this }

 

12345678910111213
switch(2)
{
case1: // Doesn't match!
std::cout<<1<<'n'; // skip case2:// Matched! std::cout<<2<<'n'; // code execution starts here case3: std::cout<<3<<'n'; // this will also be executed
case4: std::cout<<4<<'n'; // and this
default: std::cout<<5<<'n'; // and this
}

Result:

2
3
4
5

And that's definitely not what we need! When execution moves from one case to the next, it is called fall-through. Programmers almost never use fall-through, so in the rare cases when it is still used, the programmer leaves a comment in which he reports that fall-through is intentional.

Multiple statements inside the switch block

Another oddity in switch is that you can use multiple statements under each case without defining a new block:

<textarea wrap="soft" class="urvanov-syntax-highlighter-plain print-no" data-settings="" readonly="" style="-moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4; font-size: 13px !important; line-height: 20px !important;" > switch (3) { case 3: std::cout << 3; boo(); std::cout << 4; break; default: std::cout << "default casen"; break; }
1234567891011
switch(3){ case3: std::cout<<3; boo(); std::cout<<4; break; default: std::cout<<"default casen"; break;}