Here you learn how to write switch case statement in JavaScript.
javascript switch case usage:To understand when to use switch case in javascript programming, you need to know following characteristic.
default
keyword, so when there is no matching case the default will get executed. break
keyword indicates when there any matching case executed and hit the break keyword, the logic will come out of switch, it will not check for next case. Javascript Switch case statement is a type of conditional logic, what switch case does, you can also do same thing using if else in javascript, but switch case is much faster in terms of performance.
switch (valueExpression) { case 1: // code here break; case 2: // code here break; default: }
In switch case can be any data type, normally we use integer or string, above is the example of an integer switch case
If switch case value is string, then we need to use “case-1”
for each case.
switch (valueExpression) { case "value-1": // code here break; case "value-2": // code here break; default: }
In switch case statement, we should always write default at the end, if no matching case found then the default block will be executed.
Let's take a look at the example of switch case
Suppose on your webpage you want to show different message to your user on each working day, and on festive day you want to show them very different personalized message and show them some gift you offer them on that day.
Now think how you write the logic, if you use if-else statement then how many if-else you would write, that will be really tedious job right?
Here switch case statment make your job easy and much smoother.
Suppose we have five working days Monday to Friday and then festive seasons like Navratri, Kalipuja, Eid, Christmas etc.
Here is the code for javascript switch case function
<script> function displayGreetings(dayOption) { var _greetingMessage = null; var _action = null; switch (dayOption) { case "Monday": _greetingMessage = "Hey! Have a great week ahead!"; break; case "Friday": _greetingMessage = "Hey! Have a great weekend!!"; break; case "Navratri": { _greetingMessage = "Happy Navratri"; _action = "Send a box of Kaju Katli"; } break; case "Kalipuja": { _greetingMessage = "Happy Kalipuja"; _action = "Send a box of Rasgulla"; } break; case "Eid": { _greetingMessage = "Happy Eid"; _action = "Send a box of Sheer Khurma"; } break; case "Christmas": { _greetingMessage = "Happy Christmas"; _action = "Send a box of Chocolate"; } break; default: _greetingMessage = "Hello"; } } </script>
Remember that javascript is case sensitive, so when you call the switch case function, make sure you use the exact option key.
Now we call the above switch case function, this is how you can call the function!
displayGreetings("Moday"); or displayGreetings("Navratri");
Related Topics