How to Use Enum in JavaScript (Real Patterns)

How-to basics · Updated November 22, 2026

JavaScript doesn’t have a native enum keyword like C# or Java, but you can create enum-like objects using plain objects, Object.freeze(), and Symbol. This guide shows you the most practical patterns, how to use them in real code, and how to avoid common pitfalls. You’ll learn how to define a constant set of named values, iterate over them, and use them for type-safe comparisons in your projects.

What You’ll Need

  • A code editor (VS Code, Sublime, etc.)
  • Node.js installed (or just use your browser’s console)
  • Basic familiarity with JavaScript objects and functions

Step-by-Step

  1. Decide on your enum pattern. There are two common approaches: a plain frozen object (simplest) or a Symbol-based enum (prevents accidental value collisions). For most cases, a frozen object is enough. For strict uniqueness, use Symbols.
  2. Create a simple enum object. Define an object with key-value pairs. Use uppercase keys by convention. Example:
    const Color = {
      RED: 'red',
      GREEN: 'green',
      BLUE: 'blue'
    };

    This gives you named constants. You can access them as Color.RED.

  3. Freeze the object to prevent changes. Use Object.freeze() to make the enum immutable. This prevents accidental reassignment of properties. Example:
    const Color = Object.freeze({
      RED: 'red',
      GREEN: 'green',
      BLUE: 'blue'
    });

    Now Color.RED = 'pink' will silently fail (or throw in strict mode).

  4. Use Symbol for guaranteed uniqueness. If you want to ensure that no two enum members share the same value, use Symbol(). Example:
    const Color = {
      RED: Symbol('red'),
      GREEN: Symbol('green'),
      BLUE: Symbol('blue')
    };
    Object.freeze(Color);

    Each Symbol is unique, so even if you accidentally assign the same string elsewhere, it won’t match.

  5. Add a reverse mapping (optional). If you need to get the key from a value, create a helper. For a string-based enum, you can build a reverse map:
    const Color = Object.freeze({
      RED: 'red',
      GREEN: 'green',
      BLUE: 'blue'
    });
    
    const ColorReverse = Object.freeze(
      Object.fromEntries(
        Object.entries(Color).map(([key, value]) => [value, key])
      )
    );
    // ColorReverse['red'] === 'RED'

    For Symbol enums, reverse mapping is trickier because symbols are unique; you’d need to store the key in the symbol description, but that’s not reliable. So skip reverse mapping for Symbol enums.

  6. Use the enum in your code. Replace hard-coded strings with enum references. Example:
    function paintCar(color) {
      if (color === Color.RED) {
        console.log('Painting car red');
      }
    }

    This improves readability and reduces typos.

  7. Iterate over enum values. Use Object.values() or Object.keys() to loop through all members. For string enums:
    for (const value of Object.values(Color)) {
      console.log(value); // 'red', 'green', 'blue'
    }

    For Symbol enums, Object.values() returns symbols, which you can still log but not compare to strings.

  8. Use TypeScript for true enums (optional). If you use TypeScript, you get a native enum keyword. But this guide is about plain JavaScript, so stick with the object pattern.

Common Mistakes

  • Not freezing the object. Without Object.freeze(), someone could accidentally reassign a value, leading to bugs that are hard to trace.
  • Using mutable values. If you set enum values to objects or arrays, they are mutable. Prefer strings, numbers, or Symbols.
  • Comparing enum values to raw strings. If you use string enums, you might accidentally compare to a hard-coded string that doesn't match. Always use the enum reference.
  • Assuming enum values are automatically unique. With plain string enums, you can accidentally set two keys to the same value. Use Symbols if uniqueness is critical.
  • Using enum as a variable name. In some browsers, enum is a reserved word (actually it's a future reserved word), so avoid naming your variable enum.

Tips

  • Use uppercase keys. It's a common convention to signal that these are constants.
  • Add a helper to check if a value is valid. For string enums, you can create a function:
    function isColor(value) {
      return Object.values(Color).includes(value);
    }
  • Consider using a class with static properties. If you need methods, you can create a class with static getters, but that's more verbose. The object pattern is simpler.
  • For modern JavaScript, use Object.freeze() and Symbol together. This gives you both immutability and uniqueness.
  • If you're using a bundler like webpack, you can use the enum package from npm, but it's overkill for most projects.

Troubleshooting

  • My enum values are being changed. Make sure you called Object.freeze() on the object. Also, ensure you're not reassigning the whole object (e.g., Color = something) – declare with const.
  • I get TypeError: Cannot assign to read only property in strict mode. That's expected because you froze the object. Remove the freeze if you need mutability, but you probably don't.
  • My enum values are not unique. If you used strings, you can accidentally duplicate. Switch to Symbols or add a validation that checks for duplicates at creation time.
  • I can't compare enum values to strings. If you used Symbols, they are unique and cannot be compared to strings. Use string enums if you need to compare to external data (like API responses).
  • My code works in Node but not in the browser. Check if you're using Object.fromEntries() which is ES2019 – it's supported in modern browsers, but if you need older support, use a reduce loop instead.

Frequently Asked Questions

  • Does JavaScript have a built-in enum type? No, JavaScript does not have a native enum type. You simulate it with objects, Object.freeze(), and sometimes Symbol.
  • What is the best way to create an enum in JavaScript? For most cases, use a frozen plain object with string values. If you need guaranteed uniqueness, use Symbol values inside a frozen object.
  • Can I use const for each enum value instead of an object? Yes, you can define individual constants, but grouping them in an object is cleaner and provides a namespace.
  • How do I iterate over an enum? Use Object.keys() to get keys, Object.values() to get values, or Object.entries() to get both. Works for both string and Symbol enums, but note that Symbol values are not enumerable in for...in loops – use Object.values() instead.
  • Can I use an enum as a type in JavaScript? No, JavaScript is dynamically typed, so enums don't enforce types at runtime. For compile-time type safety, consider TypeScript.
  • Is it okay to use numbers as enum values? Yes, numbers are fine, but they are less readable. Strings are more self-documenting. Avoid using objects or arrays as values because they are mutable.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.