I’m rebuilding an older Java project in JavaScript and ran into the need for enums. Since JavaScript doesn’t have native enum support like Java, I’ve been trying to find a clean and reliable JavaScript enum pattern using ES6.
Here’s my current approach:
const Colors = {
RED: Symbol(“red”),
BLUE: Symbol(“blue”),
GREEN: Symbol(“green”)
};
Object.freeze(Colors);
This prevents reassignment and mutation, and Symbols help ensure each value is unique. But I’m wondering, is this a good pattern? Are there better or more standard ES6-compatible ways to define enums in JavaScript?
I also experimented with this version for better serialization:
const enumValue = (name) => Object.freeze({ toString: () => name });
const Colors = Object.freeze({
RED: enumValue(“Colors.RED”),
BLUE: enumValue(“Colors.BLUE”),
GREEN: enumValue(“Colors.GREEN”)
});
I’m looking for something that’s safe, readable, and works well across real-world use cases. Any improvements or modern best practices you’d recommend?
I’ve ported several enterprise apps from Java to JS, and honestly, for 90% of use cases, a simple Object.freeze()
approach works wonders.
const Colors = Object.freeze({
RED: 'RED',
BLUE: 'BLUE',
GREEN: 'GREEN'
});
This style of javascript enum
is serializable, easy to debug, and super readable for teams coming from strongly-typed backgrounds. Clean, straightforward, and reliable.
Jumping in here @mark-mazay approach is spot on for most scenarios. But when I needed Java-style behavior like .name
and .ordinal
, I built a small utility class.
class Enum {
constructor(name) {
this.name = name;
Object.freeze(this);
}
toString() {
return this.name;
}
}
const Colors = Object.freeze({
RED: new Enum('RED'),
BLUE: new Enum('BLUE'),
GREEN: new Enum('GREEN'),
});
This javascript enum
setup gives you immutability and a touch of OOP flavor, great for building cleaner APIs and improving readability in shared logic.
Great points above, I’ve faced scenarios where validation and reverse lookups were critical. For that, I went with a Map
-based enum approach:
const Colors = new Map([
['RED', '#ff0000'],
['BLUE', '#0000ff'],
['GREEN', '#00ff00']
]);
// Usage
const isValid = Colors.has('RED');
const hex = Colors.get('BLUE');
This javascript enum
version is ideal for value pairing, validation, and it’s naturally iterable. Plus, reversing it is a breeze when you need a two-way lookup.