Free Web Development Online Tutorials, Learn to Code
Javascript for switch case, Free JavaScript Tutorial for Beginners, JavaScript Switch Case Example

JavaScript Switch Case Statement

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.

JavaScript Switch Case Function Example

Here is the code for switch case in javascript

<script>
function displayGreetings(dayOption)
{
    var _greetingMessage = null;
    var _action = null;
            
    switch (dayOption) 
    {
        default:
        break;
            
            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;
    }
}
            
// this is how you can call the function displayGreetings(Moday); or displayGreetings(Navratri);
</script>

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

Comment
Name
Email
Website
Subscribe