Thursday, 23 October 2025

Switch Case with Enum in JavaScript

Introduction: Hello Guys, “Welcome back” Today, I am here with another one new great 

article. In this article I explained how to use Switch Case with Enum in JavaScript.

Join our Channel  on Whtsapp and Telagram for All Updates                                    

Code for HTML Page

On The HTML page I will place the element SELECT – For displaying names of countries.

The HTML SELECT element (DropDownList) has been assigned with a JavaScript onchange event 

handler.

<select onchange="OnCountriesChange(this)">

    <option value="0">Please select</option>

    <option value="1">India</option>

    <option value="2">UAE </option>

    <option value="3">USA</option>

</select>

Creating and using Enums in JavaScript

Implementation: Inside the OnCountriesChange JavaScript function, an Array will be created. Array of objects with Key Value Pairs created which will be simulated as Enum in JavaScript. Then, a SWITCH statement will be executed and each case i.e. countries will be  verified using CASE and appropriate message will be displayed using JavaScript Alert Message Box.

<script type="text/javascript">

    function OnCountriesChange(d) {

        var colors = { "India": 1, "UAE": 2, "USA": 3 };

        switch (parseInt(d.value)) {

            case colors.Red:

                alert("India");

                break;

            case colors.Green:

                alert("UAE");

                break;

            case colors.Blue:

                alert("USA");

                break;

        }

    }

</script>

Here I am giving complete code for HTML page with JavaScript functions. You need to copy and paste the code in your HTML page for enjoying the code.

 

<head>

    <title></title>

    <style type="text/css">

        body { font-family: Arial; font-size: 10pt; }

    </style>

    <script type="text/javascript">

        function OncountriesChange(d) {

            var countries = { "India": 1, "UAE": 2, "USA": 3 };

            switch (parseInt(d.value)) {

                case countries.India:

                    alert("India");

                    break;

                case countries.UAE:

                    alert("UAE");

                    break;

                case countries.USA:

                    alert("USA");

                    break;

            }

        }

    </script>

</head>

<body>

    <form>

        <select onchange="OncountriesChangeChange(this)">

            <option value="0">select</option>

            <option value="1">India</option>

            <option value="2">UAE</option>

            <option value="3">USA</option>

        </select>

    </form>

</body>

</html>

 Conclusion: In above code, I have been explained that how to use Switch Case with Enum in JavaScript. Bye Bye and take care of yourself Developers. We will come back shortly with the new article.

Regards

Programming HUB

 

No comments:

Post a Comment