Enums in javascript (with Lodash)

PDF

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:

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:

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:

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:

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.

enum

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:

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' }.

Tags:

Leave a Reply