How to do enumerations (enum) in javascript

One of the most common mistake I see when I use a third-party javascript library is the enormous amount of “constants” that is 152 characters to ensure its uniqueness. Example, a color chooser named KikaColorChooser. If it has a constant for the type of display, it will be named something like KIKACOLORCHOOSER_DISPLAY_TYPE_SMALL (a constant of 35 characters long). Ugly.

The second most common mistake is to have a short constant name that have dozens of friends with the same name. DISPLAY_SMALL is a good example.

The solution?

[source:javascript]

// The class
function KikaColorChooser() {
}

// …implementation here…

// The display type
KikaColorChooser.displayType = {
small : 0,
big : 1
}

[/source]
Thanks to the power of anonymous objects.

The downside

After writing this article, I remarked that my first argument could not stand.

I had the constant KIKACOLORCHOOSER_DISPLAY_TYPE_SMALL and the new solution is KikaColorChooser.displayType.small. The old solution is 35 characters long and the new one, 34. And no you can’t shorten the new solution in the class by just writing this.displayType.small.

Still, you should do it just for the cleanliness of your code and to impress your friends.

  • Nicolas
    A problem with using numbers is:

    var colors = {red:0, blue:1, green:2};
    var days = {sunday:0, monday:1, tuesday:2, wednesday:3, thursday:4, friday:5, saturday:6};

    colors.red == days.sunday!

    You can avoid mixing numbers with real values of the enum by using this:
    var colors = {red:{}, blue:{}, green:{}};

    This creates empty objects to use as enum values. They can only compare with themselves. They will never be equal to anything else, like value of another enum.
blog comments powered by Disqus