how does it work?I actually cannot think of a real situation where you would use switch statement. Other than if you are in different classes for instance, biology, chemistry, math, computer science and they are not interconnected. You need to store grades for each subject, then yeah, switch is useful! Otherwise, just know the syntax.
|
switch statement live |
Example 1 |
Example 2 |
var orderType = prompt ("What type is your transaction?", " ");
var shipMethod; switch (orderType) { case 'business': shipMethod = 'FedEx'; break; case 'personal': shipMethod = 'UPS Ground'; break; default: shipMethod = 'USPS'; } console.log(shipMethod); |
var orderType = 'unknown';
var shipMethod; switch (orderType) { case 'busines': case 'perosnal': shipMethod = 'UPS Ground'; break; default: shipMethod = 'USPS'; } console.log(shipMethod); |
var totalOrder = prompt ("Enter your total price", "");
var discount; switch (true) { case totalOrder >=20 && totalOrder < 75: discount = 10; break; case totalOrder >=75 && totalOrder < 100: discount = 40; break; case totalOrder >=100: discount = 50; break; default: discount = 0; } console.log("You have saved " + discount + " dollars"); |