The switch case statement is a conditional statement like if else statement. If you want to execute one of the multiple code blocks than Switch is useful.
switch statement is used to execute one code from multiple expressions.
switch(expression) {
case n:
//code block
break;
case n:
//code block
break;
default:
//default code block
}
Break Statement : In switch case, break statement is used so that next conditions won’t be checked after finding the required condition.
What is default value ?
Default in a switch statement is used to group all other values that are not specified that come into it, instead of having to specify all of them. You don’t need a default statement, as long as you know all the values that you will encounter in the variable that the switch statement is considering.
Example:
let day = 5;
switch (day) {
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";
}
console.log(`Today is ${day}`)
Today is Friday
In the above program, an expression day =
5 is evaluated with a switch
statement.
- The expression’s result is evaluated with
case 1
which results infalse
. - Then the
switch
statement goes to the 2nd case. which results infalse
. - Then the
switch
statement goes to the 3rd case. which results infalse
. - Then the
switch
statement goes to the 4th case. which results infalse
. - Then the
switch
statement goes to the 5th case. The expression’s result matches withcase
5. So the value “Today is Friday“ is is displayed. - The
break
statement terminates the block and control flow of the program jumps to outside of theswitch
block.
Example 2:
let x = 20;
switch (x) {
case 1:
x = 'one';
break;
case 2:
x = 'two';
break;
default:
x = 'Not found';
break;
}
console.log(x);
Not found
Switch vs if…else
Switch case | If else |
---|---|
It has more readable syntax | It has less readable syntax |
Multiple cases can be processed if we remove the break statement | Multiple if blocks can not be processed unless each condition is true |
It works fast for large values because the compiler creates a jump table | It is relatively slow for large values |
It’s input is an expression that can be an enumerated value of a string object | Its input is an expression that can be a specific condition or a range |
- The switch case statement executes a block of code depending on different cases.
- Break statement is used so that next conditions won’t be checked after finding the required condition.