WebTrainingRoom Online Courses
Learn JavaScript, Free JavaScript Tutorial for Beginners, Interactive JavaScript Examples

Switch Case Statement in JavaScript

Switch case, break in Javascript

Javascript Switch case statement is also 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.

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.

Switch Case Example

Here is the code for switch case in javascript

function displayGreetings(dayOption)
var _greetingMessage = null;
var _action = null;
switch (dayOption) {
case "Monday":
_greetingMessage = "Hey! Have a great week ahead!";
case "Friday":
_greetingMessage = "Hey! Have a great weekend!!";
case "Navratri":
_greetingMessage = "Happy Navratri";
_action = "Send a box of Kaju Katli";
case "Kalipuja":
_greetingMessage = "Happy Kalipuja";
_action = "Send a box of Rasgulla";
case "Eid":
_greetingMessage = "Happy Eid";
_action = "Send a box of Sheer Khurma";
case "Christmas":
_greetingMessage = "Happy Christmas";
_action = "Send a box of Chocolate";
// this is how you can call the function displayGreetings(Moday); or displayGreetings(Navratri);

Remember that javascript is case sensitive, so when you call the switch case function, make sure you use the exact option key.

Name Email Website
Javascript Switch Case Statement, Learn JavaScript Syntax

Switch case example in JavaScript