Open In App

Enums in JavaScript

Last Updated : 16 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Enums in JavaScript are used to define a set of named constants and make your code more readable and easier to understand. Instead of using random numbers or strings, enums give meaningful names to values, helping you avoid errors and improve maintainability. They're a simple way to group related values together.

Why Use Enums?

Enums are helpful because they make your code cleaner and more organized. Here's why they’re useful:

  • Enhanced Readability: Enums make code more understandable by replacing arbitrary values (like numbers or strings) with descriptive, meaningful names.
  • Better Maintainability: Enums centralize related constants in one place, making it easier to update and manage them throughout the codebase.
  • Reduced Errors: By restricting possible values to a predefined set, enums help prevent errors caused by invalid or inconsistent values.

Creating Enums in JavaScript

Here are the ways you can declare an enum in JavaScript:

1. Using Plain Objects

A simple way to simulate enums is by using objects. You can define each key-value pair in an object to represent an enum value.

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

console.log(Color.RED);
console.log(Color.GREEN);
  • Here, we're creating an enum called Color that holds the values RED, GREEN, and BLUE, each associated with a string value.
  • When you log Color.RED, it outputs the string "red".

2. Using Object.freeze() for Immutability

To ensure that the enum can't be changed or modified, you can use Object.freeze(). This makes the object and its properties immutable.

JavaScript
const Days = Object.freeze({
    SUNDAY: 0,
    MONDAY: 1,
    TUESDAY: 2,
    WEDNESDAY: 3,
    THURSDAY: 4,
    FRIDAY: 5,
    SATURDAY: 6
});

Days.SUNDAY = 7; 
console.log(Days.SUNDAY);
  • We create an enum Days using Object.freeze() to make it immutable. The values represent the days of the week.
  • Even though we try to modify Days.SUNDAY, it remains unchanged because the object is frozen.

3. Using a Class for More Flexibility

If you need more flexibility, like adding methods to your enums, you can define them as classes.

JavaScript
class Role {
    static ADMIN = "admin";
    static USER = "user";
    static GUEST = "guest";

    static isValid(role) {
        return [Role.ADMIN, Role.USER, Role.GUEST].includes(role);
    }
}

console.log(Role.ADMIN);
console.log(Role.isValid("admin"));
console.log(Role.isValid("moderator"));
  • We define a Role class with static properties for different roles (ADMIN, USER, GUEST).
  • We also add a static method isValid to check if a given role is valid.

4. Iterating Over Enums

You can easily iterate over the keys or values of your enum-like objects using Object.keys() or Object.values().

JavaScript
const Days = Object.freeze({
    MONDAY: "Monday",
    TUESDAY: "Tuesday",
    WEDNESDAY: "Wednesday"
});

Object.keys(Days).forEach(day => {
    console.log(day);
});

Object.values(Days).forEach(dayValue => {
    console.log(dayValue);
});
  • We use Object.keys() to get an array of the enum's keys (like MONDAY, TUESDAY), and we print them out.
  • We also use Object.values() to get the actual values (like "Monday", "Tuesday") and log them

Best Use Cases for Enums in JavaScript

Enums are useful in many scenarios:

  • State Management: When managing states or statuses of an object, such as "loading", "completed", or "failed".
  • User Roles: Defining roles like "admin", "user", or "guest" in your application.
  • Event Types: Categorizing different types of events like "click", "submit", or "focus".
  • Error Codes: Representing different error states in your application.

Pros and Cons of Enums in JavaScript

ProsCons
Improves code readabilityNo built-in enum support
Prevents magic valuesCan be cumbersome to manage in large apps
Reduces errors from incorrect valuesMay add some overhead for simple tasks
Ensures constant valuesRequires extra syntax or methods (like Object.freeze)

Next Article

Similar Reads