JavaScript doesn't natively support enums like languages such as TypeScript or Java, but you can simulate enum-like behavior using ES6 features. Enums (short for "enumerations") are useful when you want to define a set of named constants that represent a group of related values — like days of the week, user roles, or states.
Using const and Objects
The most common way to create enums in JavaScript is with a const object.
const Colors = {
RED: 'RED',
GREEN: 'GREEN',
BLUE: 'BLUE'
};
console.log(Colors.RED); // Output: RED
- This method is simple and keeps your values organized and readable.
- It's good for grouping related constants together.
Using Object.freeze() for Immutability
To prevent changes to your enum object, use Object.freeze():
const Status = Object.freeze({
PENDING: 'PENDING',
IN_PROGRESS: 'IN_PROGRESS',
COMPLETED: 'COMPLETED'
});
This makes the enum immutable — no one can accidentally modify or add properties.
Using Symbol for Unique Values
If you need unique and non-string values, use ES6 Symbol:
const Direction = {
UP: Symbol('UP'),
DOWN: Symbol('DOWN'),
LEFT: Symbol('LEFT'),
RIGHT: Symbol('RIGHT')
};
Symbols guarantee uniqueness, even if two enums have the same name.
Summary:
- Use objects for basic enums.
- Use Object.freeze() for safety.
- Use Symbol for uniqueness and to avoid value collisions.
While JavaScript doesn’t offer true enums natively, these ES6 patterns give you the power and flexibility to simulate them effectively.