Javascript doesn’t natively support enums and it’s not included in the ECMAScript specification. Here are a couple of ways to do that in Javascript
What is an enum?
Essentially an enum is a set of unique named constants, like UP, DOWN, NORTH, WEST, LEVEL1, LEVEL2 etc. This is a great facility, because you can use the enum names as labels or flags or modes or status or whatever you like in a very readable way. Here’s an example from Java:
1 2 3 4 | enum Direction { LEFT, RIGHT, UP, DOWN } Rocket myRocket = new Rocket(); myRocket.setDirection(Direction.UP); |
This is great right? Enums work because the constants get unique values in Java. You never need to know those values, because you equate the enum constants directly, not by their value:
1 2 3 | if (getDirection() == Direction.UP) { engageEngines(); } |
You don’t do if (getDirection() == 0)
(although this even works if UP is the first enum in the list): you compare readable names not values.
Enums in Javascript
To achieve this in Javascript, you need to emulate an enum, which is almost the same thing, except you explicitly assign the unique values initially. Observe:
1 2 3 4 | var Direction = { LEFT: 0, RIGHT: 1, UP: 2, DOWN: 3 }; var myRocket = new Rocket(); myRocket.direction = Direction.UP; |
The values don’t matter, as long as they are unique. They can be numbers, decimals, strings, arrays or anything else. Numbers are common, but the following pattern is often used as well:
1 | var Direction = { LEFT: 'LEFT', RIGHT: 'RIGHT', UP: 'UP', DOWN: 'DOWN' }; |
The advantage of this is that when you print out myRocket.direction
you don’t get a number, but the name of the constant. This is useful for logging and debugging.
Enums in Javascript with Lodash
I keep coming back to the awesome bag of tricks that is Lodash and I keep learning new things about it every day.
Here’s a way to create an enum, without explicitly defining their values:
1 | var Direction = _.keyBy(['LEFT', 'RIGHT', 'UP', 'DOWN'], _.identity); |
What happens here? _.keyBy() creates a { key: value }
object for each element in the given array and uses the function argument (second parameter) to produce the keys. _.identity simply returns the value as the key, so you end up with exactly the same as { LEFT: 'LEFT', RIGHT: 'RIGHT', UP: 'UP', DOWN: 'DOWN' }
.