- JavaScript Switch Statement
- Switch statement javascript
- Syntax of switch statement
- Flowchart of switch statement
- Example of switch statement
- Javascript switch multiple cases
- Javascript switch case multiple arguments
- How to call a function in switch case in javascript?
- Javascript nested switch statement
- Javascript switch statement vs if else
- javascript fizzbuzz switch statement
- JavaScript Switch Statement
- The JavaScript Switch Statement
- Syntax
- Example
- The break Keyword
- The default Keyword
- Example
- Example
- Common Code Blocks
- Example
- Switching Details
- Strict Comparison
- Example
- The «switch» statement
- The syntax
- An example
- Grouping of “case”
- Type matters
- Tasks
- Rewrite the «switch» into an «if»
JavaScript Switch Statement
In this tutorial, we will learn how to use the switch statement and how to use it in javascript to control the flow of the program with example.
Switch statement javascript
The switch statement is a conditional statement (just like if..else) that allows the programmer to execute different blocks of code depending on the value of a variable.
The switch statement is a more flexible version of the if-else statement because it allows the programmer to execute different blocks of code depending on the value of a variable.
Let’s first look at a simple example of the switch statement and then we will its syntax and how to use it.
Syntax of switch statement
The syntax of the switch statement is as follows:
switch (expression/variable) < case expression1: // execute if expression1 = expression break; case expression2: // execute if expression2 = expression break; . default: // execute if no match >
Let us understand the above syntax step by step.
- The switch keyword is used to start the switch statement.
- The expression is the variable that we want to check.
- The case keyword is used to start a new case block (if the expression of the switch is equal to the case expression, then execute the code inside the block).
- The expression1 is the expression for case1.
- The break keyword is used to end each case block. If you do not use the break keyword, then execution will continue to the next case block.
- The default keyword is used to start the default block.
- The break keyword is used to end the default block.
Flowchart of switch statement
The flowchart below shows the flow of the switch statement.
Example of switch statement
Let us understand the example of the switch statement with examples.
let operation = "cube"; let num = 5; switch(operation)
let message = "Hello"; switch(message)
Let’s see how the above code works:
- The first expression in a switch statement is evaluated to today’s day
- Then the value found by evaluating the expression is matched with values in each case
- if the value is matched then a block of code for that case is executed
- then break command breaks through the switch statement.
- In case no condition matched then the code block of the default section is executed
Javascript switch multiple cases
How will execute the switch statement for multiple cases?
The syntax of switch statement is as follows:
To execute switch statement for multiple cases, use a break statement for the last case that is to be run.
For example, if you want to execute a switch statement for cases 1, 2, and 3 then do not use a break statement for the first 2 cases among 3 cases. Instead, use the break statement for the last case.
Let us understand with examples.
let fruit = "Orange"; switch(fruit)
Let’s see another example of a switch statement with multiple cases.
let marks = 75; switch (marks)
Javascript switch case multiple arguments
The switch statement can also handle multiple arguments. The multiple arguments should be separated by javascript operators to be evaluated as a single value.
let a = 4, b = 5; switch (a + b) < case a + b % 2: console.log("Expression1 matched"); case a / 2 + a ^ b + a * b / 2: console.log("Expression2 matched"); break; default: console.log("Expression not matched"); >
In above example, a + b is evaluated as 4 + 5 and a / 2 + a ^ b + a * b / 2 is evaluated as (4 + 5) % 2 + (4 ^ 5) + (4 * 5) / 2 and both expressions are matched.
How to call a function in switch case in javascript?
The function can be called at the place of expression if it returns a valid value. The function can be called in the expression as well as in the case block.
You can put your function calling code in the switch case. The function calling code should be in the curly braces <> .
function sum(a, b) < return a + b; >switch(10) < case sum(1, 2): console.log("sum(1, 2)"); break; case sum(6, 4): < let output = "sum(6, 4) = " + sum(6, 4); console.log(output); >break; default: console.log("default"); >
Javascript nested switch statement
Javascript nested switch statement is similar to nested if statement. The nested switch statement is used to match values with multiple cases.
Here is an example of the nested switch statement.
let a = 1, b = 3; switch (a) < case 1: switch (b) < case 2: console.log("a = 1, b = 2"); break; case 3: console.log("a = 1, b = 3"); break; default: console.log("a = 1, b did not match"); >break; case 2: console.log("a = 2"); break; default: console.log("a did not match"); >
Javascript switch statement vs if else
Javascript switch statement is less efficient than if-else statement. (see the example below)
The if-else statement is used when there are multiple cases to match. The switch statement is used when there are multiple cases to match and the cases are not mutually exclusive.
console.time('if else'); for (let i = 0; i < 9999999; i++) < if (i % 2 == 0) < >else < >> console.timeEnd('if else'); console.time('switch'); for (let i = 0; i < 9999999; i++) < switch (i % 2) < case 0: break; case 1: break; >> console.timeEnd('switch');
Output : result may vary on each run depending on the processor. But if-else is always more efficient.
javascript fizzbuzz switch statement
The fizzbuzz algorithm is a simple programming task that tests your knowledge of the basic concepts of programming.
You can use the switch statement to implement the fizzbuzz algorithm.
function fizzbuzz(num) < switch (true) < case num % 3 === 0 && num % 5 === 0: return "fizzbuzz"; case num % 3 === 0: return "fizz"; case num % 5 === 0: return "buzz"; >> console.log(fizzbuzz(3)); console.log(fizzbuzz(5)); console.log(fizzbuzz(15));
JavaScript Switch Statement
The switch statement is used to perform different actions based on different conditions.
The JavaScript Switch Statement
Use the switch statement to select one of many code blocks to be executed.
Syntax
- The switch expression is evaluated once.
- The value of the expression is compared with the values of each case.
- If there is a match, the associated block of code is executed.
- If there is no match, the default code block is executed.
Example
The getDay() method returns the weekday as a number between 0 and 6.
This example uses the weekday number to calculate the weekday name:
switch (new Date().getDay()) <
case 0:
day = «Sunday»;
break;
case 1:
day = «Monday»;
break;
case 2:
day = «Tuesday»;
break;
case 3:
day = «Wednesday»;
break;
case 4:
day = «Thursday»;
break;
case 5:
day = «Friday»;
break;
case 6:
day = «Saturday»;
>
The result of day will be:
The break Keyword
When JavaScript reaches a break keyword, it breaks out of the switch block.
This will stop the execution inside the switch block.
It is not necessary to break the last case in a switch block. The block breaks (ends) there anyway.
Note: If you omit the break statement, the next case will be executed even if the evaluation does not match the case.
The default Keyword
The default keyword specifies the code to run if there is no case match:
Example
The getDay() method returns the weekday 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»;
>
The result of text will be:
The default case does not have to be the last case in a switch block:
Example
switch (new Date().getDay()) <
default:
text = «Looking forward to the Weekend»;
break;
case 6:
text = «Today is Saturday»;
break;
case 0:
text = «Today is Sunday»;
>
If default is not the last case in the switch block, remember to end the default case with a break.
Common Code Blocks
Sometimes you will want different switch cases to use the same code.
In this example case 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 = «Soon it is Weekend»;
break;
case 0:
case 6:
text = «It is Weekend»;
break;
default:
text = «Looking forward to the Weekend»;
>
Switching Details
If multiple cases matches a case value, the first case is selected.
If no matching cases are found, the program continues to the default label.
If no default label is found, the program continues to the statement(s) after the switch.
Strict Comparison
Switch cases use strict comparison (===).
The values must be of the same type to match.
A strict comparison can only be true if the operands are of the same type.
In this example there will be no match for x:
Example
let x = «0»;
switch (x) case 0:
text = «Off»;
break;
case 1:
text = «On»;
break;
default:
text = «No value found»;
>
The «switch» statement
It gives a more descriptive way to compare a value with multiple variants.
The syntax
The switch has one or more case blocks and an optional default.
- The value of x is checked for a strict equality to the value from the first case (that is, value1 ) then to the second ( value2 ) and so on.
- If the equality is found, switch starts to execute the code starting from the corresponding case , until the nearest break (or until the end of switch ).
- If no case is matched then the default code is executed (if it exists).
An example
An example of switch (the executed code is highlighted):
Here the switch starts to compare a from the first case variant that is 3 . The match fails.
Then 4 . That’s a match, so the execution starts from case 4 until the nearest break .
If there is no break then the execution continues with the next case without any checks.
In the example above we’ll see sequential execution of three alert s:
alert( 'Exactly!' ); alert( 'Too big' ); alert( "I don't know such values" );
Both switch and case allow arbitrary expressions.
let a = "1"; let b = 0; switch (+a)
Here +a gives 1 , that’s compared with b + 1 in case , and the corresponding code is executed.
Grouping of “case”
Several variants of case which share the same code can be grouped.
For example, if we want the same code to run for case 3 and case 5 :
Now both 3 and 5 show the same message.
The ability to “group” cases is a side effect of how switch/case works without break . Here the execution of case 3 starts from the line (*) and goes through case 5 , because there’s no break .
Type matters
Let’s emphasize that the equality check is always strict. The values must be of the same type to match.
For example, let’s consider the code:
let arg = prompt("Enter a value?"); switch (arg)
- For 0 , 1 , the first alert runs.
- For 2 the second alert runs.
- But for 3 , the result of the prompt is a string «3» , which is not strictly equal === to the number 3 . So we’ve got a dead code in case 3 ! The default variant will execute.
Tasks
Rewrite the «switch» into an «if»
Write the code using if..else which would correspond to the following switch :
To precisely match the functionality of switch , the if must use a strict comparison ‘===’ .
For given strings though, a simple ‘==’ works too.
if(browser == 'Edge') < alert("You've got the Edge!"); >else if (browser == 'Chrome' || browser == 'Firefox' || browser == 'Safari' || browser == 'Opera') < alert( 'Okay we support these browsers too' ); >else
Please note: the construct browser == ‘Chrome’ || browser == ‘Firefox’ … is split into multiple lines for better readability.
But the switch construct is still cleaner and more descriptive.