Switch Case Statement in JavaScript
- We can use conditional statements to execute different block of statements based on condition.
- Switch Case statement is used for selection of cases based on user input or current situation.
- Switch Case Syntax is similar to that of “Java/C/C++“.
switch(num) { case 1: Execute This Code Block 1 break; case 2: Execute This Code Block 2 break; default: Execute This Code Block if num!=1 and num!=2 }
Explanation :
- Let’s Assume user have assigned “1″ to variable num , then JS will compare num with Case number .
- If case number and value of Variable are equal then Code inside block will be executed.
- break statement is used to take control outside switch case. (in short break statement terminates switch case).
- Use break to prevent the code from running into the next case automatically.
- If variable is not equal to first case then it will compare value with next case number.
- If none of the case
Live Example :
<html> <body> <script type="text/javascript"> var d=new Date(); var theDay=d.getDay(); switch (theDay) { case 5: document.write("<b>Finally Friday</b>"); break; case 6: document.write("<b>Super Saturday</b>"); break; case 0: document.write("<b>Weekend Sunday</b>"); break; default: document.write("<b>Again work !!!</b>"); } </script> </body> </html>
Output
Weekend Sunday
Some Pretty Rules of Switch Case Statements
Rule 1 : Use of Comma Operator
switch (theDay) { case 5,1,4: document.write("<b>Finally Friday</b>"); break; case 1,2,6: document.write("<b>Super Saturday</b>"); break; case 4,5,0: document.write("<b>Weekend Sunday</b>"); break; default: document.write("<b>Again work !!!</b>"); }
Output :
Weekend Sunday
Explanation :
- Comma Operator returns rightmost value.
- Means case 1,2,3 is equivalent to case 3.
Rule 2 : Single Block is used for different Cases
switch (theDay) { case 1: case 2: case 3: case 4: case 5: case 6: document.write("<b>Weekdays</b>"); break; case 0: document.write("<b>Sunday</b>"); break; default: document.write("<b>Default</b>"); }
As break is not written after cases , Value of “theDay” if falls between 1-6 then “Weekdays” gets printed.