If you have more than three conditions, it is good practice to use the switch-case statement. The basic structure of switch-case is as shown in the following:
switch (expression) { case expression1: break; case expression2: break; case expression3: break; //------------------------------- //------------------------------- // More case //------------------------------- // ------------------------------- default: }
Every case
has a break
. However, the default
does not need a break
.
Consider that Tom has 35 pens. His friends John, Cindy, Laura, and Terry have 25, 35, 15, and 18 pens, respectively. Now, John wants to check who has 35 pens. We need to compare the number of Tom's pens with everyone's pens. We can use switch-case for this type of case. The code will be as follows:
<html> <head> <title> Switch-Case </title> </head> <body> <script type="text/javascript"> var Tom = 35; switch (Tom) { case 25: //Number of John's pens document.write("John has equal number of pens as Tom"); break; case 35: //Number of Cindy's pens document.write("Cindy has equal number of pens as Tom"); break; case 15: //Number of Laura's pens document.write("Laura has equal number of pens as Tom"); break; case 18: //Number of Terry's pens document.write("Terry has equal number of pens as Tom"); break; default: document.write("No one has equal pens as Tom"); } </script> </body> </html>
The output will be as follows:
%
).)