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?