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
- 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. - 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. - 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). - Use
Symbolfor guaranteed uniqueness. If you want to ensure that no two enum members share the same value, useSymbol(). Example:const Color = { RED: Symbol('red'), GREEN: Symbol('green'), BLUE: Symbol('blue') }; Object.freeze(Color);Each
Symbolis unique, so even if you accidentally assign the same string elsewhere, it won’t match. - 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.
- 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.
- Iterate over enum values. Use
Object.values()orObject.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. - Use TypeScript for true enums (optional). If you use TypeScript, you get a native
enumkeyword. 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
enumas a variable name. In some browsers,enumis a reserved word (actually it's a future reserved word), so avoid naming your variableenum.
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()andSymboltogether. This gives you both immutability and uniqueness. - If you're using a bundler like webpack, you can use the
enumpackage 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 withconst. - I get
TypeError: Cannot assign to read only propertyin 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 sometimesSymbol. - 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
Symbolvalues inside a frozen object. - Can I use
constfor 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, orObject.entries()to get both. Works for both string and Symbol enums, but note that Symbol values are not enumerable infor...inloops – useObject.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
- Reaction Time Test Traffic Light: How It Works
- How to Say “Update” in 12 Languages
- Windows Symbol Shortcuts: Alt Codes & More
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Google Sheets IFS With Text: Syntax, Examples, and TipsYes—Google Sheets’ IFS function can test text directly: put the text in double quotes in each condition, then…
- Google Sheets: Count Checked Checkboxes with COUNTIFTo count checked checkboxes in Google Sheets, use =COUNTIF(B2:B20,TRUE), replacing B2:B20 with the cells that contain your checkboxes.…
- Delete a Page in Word Using Ctrl+G: Step-by-Step GuideTo delete a page in Word with Ctrl+G on Windows, press Ctrl+G, enter \page in the Go To…
- Break External Links in Excel: Safe Ways to Remove ThemTo break an external workbook link in Excel for Microsoft 365 on Windows, save a backup, then select…
- Track Changes in Word: How to Remove ThemTo get rid of Track Changes in Word, first turn tracking off, then accept or reject the recorded…
- Excel Remove Everything but Duplicates: Keep RepeatsYes. To remove everything but duplicates in Excel, count how often each value or row occurs, keep records…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.