Skip to content

Instantly share code, notes, and snippets.

@justinbmeyer
Created March 28, 2012 19:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinbmeyer/2229611 to your computer and use it in GitHub Desktop.
Save justinbmeyer/2229611 to your computer and use it in GitHub Desktop.
Enums in JavaScript

Reasons to Use Enums:

  1. Easier to Debug / more likely to give errors.
  2. Can look up available properties.
  3. Property values changes.

Lets break each of these down:

Easier to debug / more likely to give errors

The following does not error, it returns undefined:

({}).SOMEPROPERTY //-> undefined

So something like:

topic.layout(X5.primitives.TopicGrowthDirections.TREEE)

would not error, and instead likely result in a read of the layout.

Contrast this to:

topic.layout("tree")

Where layout looked like:

{
  layout : function(newVal){
     if(newVal === undefined){
       // getter
     } else {
       var enumVal = X5.primitives.TopicGrowthDirections[newVal]
       if(!enumVal) { throw "WRONG VAL" }
       // continue setter
     }
  }
}

This will throw "WRONG VAL" if an incorrect propertyName of the enum is provided.

Can look up available properties

You can still look at X5.primitives.TopicGrowthDirections for values one can pass into layout. There is no difference between using layout() to do enum lookup or passing the enum value to layout.

Property values changes

Enums are typically used to allow changes to the "value" part of the enum. For TREE, it allows you to change "layout_tree" in one place.

Both using enums inside and outside layout() allow "layout_tree" to change just as easily.

However, if TREE changes, there is a difference.

Searching for X5.primitives.TopicGrowthDirections.TREE would undoubtedly give you fewer results than TREE or tree. However, I'd argue that changing enum property names is very uncommon and unlikely. I've never needed to do this.

Finally ....

The reason to do this:

  1. By providing "tree" you will actually get better warnings.
  2. You have to write less code.

IMO, these reasons win out against the unlikely event that "TREE" needs to change to "WEB" or something (especially given the mature nature of mindjet's feature set).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment