Enums in Javascript with ES6
Is there a problem with this formulation?
I don't see any.
Is there a better way?
I'd collapse the two statements into one:
const Colors = Object.freeze({ RED: Symbol("red"), BLUE: Symbol("blue"), GREEN: Symbol("green")});
If you don't like the boilerplate, like the repeated Symbol
calls, you can of course also write a helper function makeEnum
that creates the same thing from a list of names.
Whilst using Symbol
as the enum value works fine for simple use cases, it can be handy to give properties to enums. This can be done by using an Object
as the enum value containing the properties.
For example we can give each of the Colors
a name and hex value:
/** * Enum for common colors. * @readonly * @enum {{name: string, hex: string}} */const Colors = Object.freeze({ RED: { name: "red", hex: "#f00" }, BLUE: { name: "blue", hex: "#00f" }, GREEN: { name: "green", hex: "#0f0" }});
Including properties in the enum avoids having to write switch
statements (and possibly forgetting new cases to the switch statements when an enum is extended). The example also shows the enum properties and types documented with the JSDoc enum annotation.
Equality works as expected with Colors.RED === Colors.RED
being true
, and Colors.RED === Colors.BLUE
being false
.
This is my personal approach.
class ColorType { static get RED () { return "red"; } static get GREEN () { return "green"; } static get BLUE () { return "blue"; }}// Use case.const color = Color.create(ColorType.RED);