Thursday, May 8, 2014

JavaScript Enums

We all know the advantages of enums. These help code readability, reduce hard coding and much more. Wouldn’t be great we have the same support in our javascript code. Unfortunately javascript does not provide this support out of box. There are several ways you can accomplish this functionality. In this blog I will show one such approach.
Javascript provides a loose syntax where you can specify your properties without first defining them. I will take advantage of this and define my enums as below.
    this.enum = new Object();

    this.enum.notesType = {
        New: 1,
        Correct: 2,
        Saved: 3,
        Default: 4
    };

    this.enum.fieldType = {
        Notes: 0,
        Patient: 1,
        Default: 2
    };

As you see, I first initialized a variable called enum. I used the name “enum” to say that all the properties of this object are of enum values. Later I define an enum similar to what we do in a traditional server side code such as C#. Now this enum can be used in our code as below:
    if (notestype === enum.notesType.Default) {
        //do something
    }

With this little trick we can bring the enums we know to javascript. Wait a minute we can even make it better in javascript. Check this enum definition
    this.enum.module = {
        patient: 'patient',
        user: 'user'
    };

That’s correct we can define strings in javascript enums, which is not possible in C#.

No comments:

Post a Comment