Enums in Javascript with ES6

19    Asked by kingsl_8090 in Java , Asked on May 13, 2025

What are enums in JavaScript and how can you implement them using ES6 features? While JavaScript doesn’t have built-in enums like some other languages, learn how you can simulate enum behavior using objects, const, or Symbol for cleaner, more readable code.

Answered by JohnHill

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.



Your Answer

Interviews

Parent Categories