Switch-case
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...