Writing Your Own JavaScript Library – Enums

April 8, 2012

no comments

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
        break;
    case enumExample.Value2:
        // do something else
        break;
    default:
        break;
}

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.

Summary

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.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>