{{ !articles[0].partner.isSponsoringArticle ? "Platinum" : "Portal" }} Partner

Writing Your Own JavaScript Library – Enums

Continuing the post series about writing a JavaScript library, in this post I’m going to show how to create enums in JavaScript.

JavaScript Enums

If you use an object oriented language you probably used enums in your code. Enums are strongly typed constants that assign meaningful names to integer values. Then, instead of using magical integers all over your code you will use an enum instead. When writing an API or a library (not necessary in JavaScript), it is very helpful to create enums to express your integer constants. Using enums can help making your code more expressive to its users and more maintainable to you (you don’t need to remember what you meant when you used some integer value in your code).

JavaScript doesn’t include implementation for enums out of the box. On the other hand, JavaScript is a dynamic language and therefore you can mimic enums behavior by using an object literal. Here is an example of creating a JavaScript enum:

var enumExample = {
    Value1: 0,
    Value2: 1,
    Value3: 2

In the example, an enum is created with the name enumExample. It is assigning three values with the constants of 0, 1 and 2. In order to use the previously created enum you can write code such as:

var someValue = enumExample.Value1;

// this code can appear later in the code
if (someValue === enumExample.Value1) {
    // do something
switch (somevalue) {
    case enumExample.Value1:
        // do something
    case enumExample.Value2:
        // do something else

Writing an Enum in JavaScript Library

Here is an example of adding an enum to the library from the previous post:

(function (ns) {
    ns.enumExample = {
        Value1: 0,
        Value2: 1,
        Value3: 2
}(this.ns = this.ns || {}));

In the example an enum is added to the library’s namespace and will be exposed to the library’s users.


In the post I explained how to create a JavaScript enum and how to expose it through the JavaScript library. Using enums can help to create a much more expressive and meaningful API. Creating meaningful code might help the library users to adopt the library much faster.




Published at DZone with permission of {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks