What is the preferred syntax for defining enums in JavaScript? Something like:
my.namespace.ColorEnum = {
RED : 0,
GREEN : 1,
BLUE : 2
}
// later on
if(currentColor == my.namespace.ColorEnum.RED) {
// whatever
}
Or is there a more preferable idiom?
In most modern browsers, there is a symbol primitive data type which can be used to create an enumeration. It will ensure type safety of the enum as each symbol value is guaranteed by JavaScript to be unique, i.e.
Symbol() != Symbol()
. For example:To simplify debugging, you can add a description to enum values:
Plunker demo
On GitHub you can find a wrapper that simplifies the code required to initialize the enum:
IE8 does Not support freeze() method.
Source: http://kangax.github.io/compat-table/es5/, Click on "Show obsolete browsers?" on top, and check IE8 & freeze row col intersection.
In my current game project, I have used below, since few customers still use IE8:
We could also do:
or even this:
The last one, seems most efficient for string, it reduces your total bandwidth if you have server & client exchanging this data.
Of course, now it's your duty to make sure there are no conflicts in the data (RE, EX, etc. must be unique, also 1, 2, etc. should be unique). Note that you need to maintain these forever for backward compatibility.
Assignment:
Comparision:
I came up with this approach which is modeled after enums in Java. These are type-safe, and so you can perform
instanceof
checks as well.You can define enums like this:
Days
now refers to theDays
enum:The implementation:
This isn't much of an answer, but I'd say that works just fine, personally
Having said that, since it doesn't matter what the values are (you've used 0, 1, 2), I'd use a meaningful string in case you ever wanted to output the current value.
your answers are far too complicated
As of writing, October 2014 - so here is a contemporary solution. Am writing the solution as a Node Module, and have included a test using Mocha and Chai, as well as underscoreJS. You can easily ignore these, and just take the Enum code if preferred.
Seen a lot of posts with overly convoluted libraries etc. The solution to getting enum support in Javascript is so simple it really isn't needed. Here is the code:
File: enums.js
And a test to illustrate what it gives you:
file: enumsSpec.js
As you can see, you get an Enum factory, you can get all the keys simply by calling enum.keys, and you can match the keys themselves to integer constants. And you can reuse the factory with different values, and export those generated Enums using Node's modular approach.
Once again, if you are just a casual user, or in the browser etc, just take the factory part of the code, potentially removing underscore library too if you don't wish to use it in your code.