JAVASCRIPT

JavaScript Enum: Syntax, Usage, and Examples

JavaScript doesn't have built-in support for enums like some other programming languages (such as TypeScript or Java), but you can still create similar structures using objects. A JavaScript enum helps you define a fixed set of named values that make code easier to read, maintain, and debug. Developers use these enums to represent sets of options like days of the week, user roles, directions, or status types.

How to Create a JavaScript Enum

You can simulate an enum in JavaScript using plain objects. Here’s the basic syntax:

const Direction = {
  UP: "UP",
  DOWN: "DOWN",
  LEFT: "LEFT",
  RIGHT: "RIGHT"
};

Each property in the object represents a possible value. Since objects are key-value stores, you can access the values like this:

console.log(Direction.UP); // "UP"

This format gives you the flexibility of strings while enforcing a limited set of values.

When to Use Enum JavaScript Patterns

Enums make your code cleaner, more expressive, and easier to work with—especially when dealing with known, limited options. Use them when:

You Need to Define a Set of Related Constants

const Status = {
  PENDING: "PENDING",
  APPROVED: "APPROVED",
  REJECTED: "REJECTED"
};

This works well when managing state, user permissions, or predefined options.

You Want to Prevent Hardcoded Values

function handleRole(role) {
  if (role === UserRole.ADMIN) {
    grantAdminAccess();
  }
}

Avoiding repeated string literals helps you catch typos and centralizes control.

You Need Code That’s Easier to Maintain

Instead of writing:

if (user.role === "editor") {
  // Do something
}

You can define:

const Role = {
  EDITOR: "editor",
  ADMIN: "admin",
  GUEST: "guest"
};

if (user.role === Role.EDITOR) {
  // Do something
}

Now, updating or changing the role names only requires changing the enum.

Examples of Enum in JavaScript

Basic Enum Pattern

const Weekday = {
  MONDAY: "Monday",
  TUESDAY: "Tuesday",
  WEDNESDAY: "Wednesday",
  THURSDAY: "Thursday",
  FRIDAY: "Friday"
};

function isWorkday(day) {
  return day !== Weekday.SATURDAY && day !== Weekday.SUNDAY;
}

This avoids string repetition and keeps logic clean.

Using JavaScript Enum for Switch Statements

const OrderStatus = {
  NEW: "new",
  PROCESSING: "processing",
  COMPLETED: "completed"
};

function handleOrder(status) {
  switch (status) {
    case OrderStatus.NEW:
      console.log("Create new order entry");
      break;
    case OrderStatus.PROCESSING:
      console.log("Track progress");
      break;
    case OrderStatus.COMPLETED:
      console.log("Close order");
      break;
  }
}

Enums in JavaScript are perfect for this kind of control flow.

Freeze Enum to Prevent Modification

JavaScript lets you change object properties unless you explicitly prevent it. Use Object.freeze() to make your enum immutable:

const Priority = Object.freeze({
  HIGH: "high",
  MEDIUM: "medium",
  LOW: "low"
});

Trying to change Priority.HIGH after freezing won’t work.

JavaScript Enum Type Checking

You can check if a value belongs to the enum using Object.values():

function isValidPriority(value) {
  return Object.values(Priority).includes(value);
}

This helps validate function arguments or incoming data.

Learn More About Enums in JavaScript

Enum Values as Numbers

Sometimes, you might want enums with numeric values:

const Size = {
  SMALL: 1,
  MEDIUM: 2,
  LARGE: 3
};

This allows comparison, sorting, or even arithmetic logic.

if (Size.SMALL < Size.LARGE) {
  console.log("Small is less than large");
}

Enums and Reverse Lookup

If your enum values are unique, you can implement reverse lookup manually:

const Color = {
  RED: "red",
  BLUE: "blue",
  GREEN: "green"
};

function getKeyByValue(enumObj, value) {
  return Object.keys(enumObj).find(key => enumObj[key] === value);
}

console.log(getKeyByValue(Color, "blue")); // "BLUE"

This can help in debugging or user interfaces where you want to map a value back to its label.

Enum in JavaScript with Symbols

For better uniqueness and avoiding collisions, you can use Symbol:

const TrafficLight = {
  RED: Symbol("RED"),
  YELLOW: Symbol("YELLOW"),
  GREEN: Symbol("GREEN")
};

Now even if two enums share the same name, their values won’t match unless they’re from the same enum.

console.log(TrafficLight.RED === TrafficLight.GREEN); // false

Symbols prevent accidental overlap and are ideal for internal use.

Enum vs Object Lookup Table

Sometimes you’ll hear enums compared to lookup tables. In practice, they’re similar—but enums usually define constants, while lookup tables often hold behaviors or data:

const CurrencySymbol = {
  USD: "$",
  EUR: "€",
  GBP: "£"
};

Whether it’s technically an enum or not, the pattern is the same: define a controlled list of values in one place.

Alternatives Using Maps or Sets

When enums need dynamic behavior or iteration, consider Map or Set:

const StatusMap = new Map([
  ["active", "Active user"],
  ["inactive", "Inactive user"],
  ["banned", "Banned user"]
]);

console.log(StatusMap.get("banned")); // "Banned user"

Maps give you built-in methods like .get() and .has() but lack the immutability of frozen enums.

The enum JavaScript pattern gives structure and predictability to code that deals with predefined sets of values. While JavaScript doesn’t support enums natively, using objects, constants, or Symbols provides a flexible way to implement them.

These pseudo-enums improve readability, make refactoring easier, and reduce bugs caused by inconsistent values. Enums in JavaScript may not be formal language features, but they’re a well-established and practical part of writing maintainable, robust code.

Learn to Code in JavaScript for Free
Start learning now
button icon
To advance beyond this tutorial and learn JavaScript by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH