Switch Case is a multi-way decision statement.This match the value of variable given by end user against a list of “case” values and when a match is found , a block of statements associated with that case executed.
Syntax:-
switch(expression) { case value1: block1; break; case value2: block2; break; --------------------- --------------------- case value n: block n; break; default: default-block; break; }
Working of Switch Case:
- Expression of switch is evaluated.
- Value of expression is compared with value of each case.
- If the value match then associated code of that block executed.
- If there is no match then default case executed.
Example:-
<!DOCTYPE html> <html> <body> <h3>Switch Case</h3> <p id="demo"></p> <script> let day; 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"; } document.getElementById("demo").innerHTML = "Today is " + day; </script> </body> </html>
Explain example:- In above example getDay() method returns the weekday as a number from 0 to 6.
Sunday=0, Monday=1,……..Saturday=6 and in example above we create the cases bases on these numbers.If getDay() return ‘0’ first case will execute and return ‘Sunday’ and so on.
default keyword: The default keyword in script specify that if there is no case match then default block will execute.
break keyword: It breaks out of the switch block.As break keyword come this will stop the execution inside the switch block.If you miss the break statement, the next case will be executed even if the evaluation does not match the case.
Difference between conditional statement and Switch Case
Switch Case | If-Else |
It is easy to edit switch cases as they are recognized easily. | It is difficult to edit Nested If-Else statement |
In Switch int and char data type can used. | In this int,float,char and double data type can used |
Switch statement is used to select among multiple alternatives. | if statement is used to select among two alternatives. |