How to create and use Enums in JavaScript
 
Author:
Filed Under: JavaScript
Published Date: Nov 03, 2011
Views: 744
 

Abstract: Here Mudassar Ahmed Khan has explained how to create and use Enums (Enumeration) in JavaScript.

Comments:  0

 

In this article I will explain how to create and use Enums in JavaScript. JavaScript does not have any enum data type but still we can create an array of key value pair and use it as enum.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type = "text/javascript">
        var colors = { "Red": 1, "Green": 2, "Blue": 3 };
        function DropdownChange(d) {
            switch (parseInt(d.value)) {
                case colors.Red:
                    alert("Red");
                    break;
                case colors.Green:
                    alert("Green");
                    break;
                case colors.Blue:
                    alert("Blue");
                    break;
            }
        }
    </script>
</head>
<body>
    <form>
        <select onchange = "DropdownChange(this)">
            <option value = "1">Red Color</option>
            <option value = "2">Green Color</option>
            <option value = "3">Blue Color</option>
        </select>
    </form>
</body>
</html>
 
In the above example I have created a simple enum of 3 colors Red, Green and Blue to which I have assigned integer values 1, 2 and 3 respectively. Now on the change of the HTML SELECT dropdown the function DropdownChange is called which based on the selected value displays the selected color in Alert
Note: Since by default JavaScript does not have any Enum data type nor it has type safety hence one can easily set any value to the Enums and modify them.
Demo:








Related Articles



Comments

No comments have been added to this article.

Add comments

You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment

Please note that all comments are moderated and will be deleted if they are
  • Not relavant to the article
  • Spam
  • Advertising campaigns or links to other sites
  • Abusive content.
Please do not post code, scripts or snippets.

Name*: Required
Email*: Required
Comment*: Required
Security code*: CaptchaInvalid Security Code
  Submit