Table of contents
1.
Introduction
2.
What Are Enums?
2.1.
Simulating Enums in JavaScript
2.2.
Example: Using Enums in a Function
3.
Creating Enums using Plain Objects
3.1.
Example
3.2.
Why Use Objects for Enums?
3.3.
Limitations of This Approach
4.
Using Object.freeze() Method
4.1.
Example
5.
Using a Class for More Flexibility
5.1.
Example
6.
Iterating Over Enums
6.1.
Example
7.
Key Features of Enums in JavaScript
8.
When to Use Enums in JavaScript?
8.1.
1. Working with a Fixed Set of Values
8.2.
2. Improving Code Readability
8.3.
3. Preventing Typos & Errors
8.4.
4. Simplifying Refactoring
8.5.
When Not to Use Enums
9.
Best Use Cases for Enums in JavaScript
10.
Pros and Cons of Enums in JavaScript
10.1.
Pros
10.2.
Cons
11.
Class-Based Approach
11.1.
Why Use a Class-Based Approach?
11.2.
Example: Implementing a DaysOfWeek Enum Using Classes
11.3.
Adding Custom Methods
11.4.
Enforcing Type Safety
11.5.
Iterating Over Enum Values
11.6.
When to Use the Class-Based Approach
12.
Does JavaScript Support Enum?
13.
Frequently Asked Questions
13.1.
What is an enum in JavaScript?
13.2.
How can I make enums immutable?
13.3.
What are the best use cases for enums?
14.
Conclusion
Last Updated: Jan 12, 2025
Easy

JavaScript Enum

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

JavaScript Enum is a feature that allows developers to define a set of named constants. These constants are grouped together and can be used throughout the program, making the code more readable and easier to manage. Enums help in reducing errors by ensuring that only valid values are used in a specific context. While JavaScript does not have a built-in enum type like some other programming languages, developers can create enums using objects.

JavaScript Enum

In this article, you will learn how to create and use JavaScript enums, along with their syntax and practical applications.

What Are Enums?

Enums are a collection of named values that represent a specific set of constants. For example, if you are working with days of the week, you might want to define constants like `Monday`, `Tuesday`, etc. Instead of using raw strings or numbers, enums make your code more readable & less error-prone.

Simulating Enums in JavaScript

Since JavaScript does not have native enum support, developers often use objects to simulate enums. Let’s see how you can create an enum-like structure in JavaScript:

const DaysOfWeek = {
  Monday: "Monday",
  Tuesday: "Tuesday",
  Wednesday: "Wednesday",
  Thursday: "Thursday",
  Friday: "Friday",
  Saturday: "Saturday",
  Sunday: "Sunday",
};

console.log(DaysOfWeek.Monday);
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

Monday


In this example, `DaysOfWeek` is an object that acts like an enum. Each property represents a constant value. This approach ensures that you can refer to days by their names instead of using arbitrary numbers or strings.

Example: Using Enums in a Function

Let’s say you want to write a function that checks if a given day is a weekend. Let’s see how you can use the `DaysOfWeek` enum:

function isWeekend(day) {
  return day === DaysOfWeek.Saturday || day === DaysOfWeek.Sunday;
}
console.log(isWeekend(DaysOfWeek.Saturday)); 
console.log(isWeekend(DaysOfWeek.Monday)); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

true
false


In this example, the `isWeekend` function uses the `DaysOfWeek` enum to check if the given day is a weekend. This makes the code more readable & less prone to errors.

Creating Enums using Plain Objects

The simplest way to create enums in JavaScript is by using plain objects. An object can hold key-value pairs, where the key is the name of the constant and the value is its associated value.

Example

const Colors = {
    RED: 'red',
    GREEN: 'green',
    BLUE: 'blue',
};
console.log(Colors.RED); 
console.log(Colors.GREEN); 
You can also try this code with Online Javascript Compiler
Run Code


Output: 

red
green


Explanation:

  1. The Colors object acts as an enum.
     
  2. Colors.RED returns the string 'red', making it more meaningful than using plain strings in your code.

Why Use Objects for Enums?

Using objects for enums has several advantages:

1. Readability: Code becomes easier to understand because you use meaningful names instead of magic numbers or strings.
 

2. Maintainability: If you need to change a value, you only need to update it in one place.
 

3. Prevents Errors: Using enums reduces the risk of typos or incorrect values in your code.

Limitations of This Approach

While using objects to simulate enums works well, it has some limitations:

1. No Type Safety: JavaScript is a dynamically typed language, so there’s no way to enforce that a variable must be one of the enum values.
 

2. No Built-in Methods: Unlike languages with native enums, JavaScript objects do not have built-in methods for iterating over enum values or checking if a value belongs to the enum.

Using Object.freeze() Method

To make an enum immutable, you can use the Object.freeze() method. This ensures that the enum values cannot be accidentally modified during program execution.

Example

const Directions = Object.freeze({
    UP: 'up',
    DOWN: 'down',
    LEFT: 'left',
    RIGHT: 'right',
});


console.log(Directions.UP); // Output: up


// Trying to modify the enum (will have no effect):
Directions.UP = 'north';
console.log(Directions.UP);
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

up
up


Explanation:

  1. Object.freeze() locks the object, preventing changes to its properties.
     
  2. Even if you attempt to modify a property, it remains unchanged.

Using a Class for More Flexibility

For more advanced scenarios, you can use a class to define enums. This approach provides additional flexibility and allows you to associate methods with the enum.

Example

class Status {
    static PENDING = 'Pending';
    static IN_PROGRESS = 'In Progress';
    static COMPLETED = 'Completed';

    static getStatusMessage(status) {
        switch (status) {
            case Status.PENDING:
                return 'Your task is pending.';
            case Status.IN_PROGRESS:
                return 'Your task is in progress.';
            case Status.COMPLETED:
                return 'Your task is completed.';
            default:
                return 'Unknown status.';
        }
    }
}
console.log(Status.PENDING);
console.log(Status.getStatusMessage(Status.IN_PROGRESS)); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

Pending
Your task is in progress.


Explanation:

  1. The Status class holds constants as static properties.
     
  2. The getStatusMessage method demonstrates how enums can be paired with logic to provide more functionality.

Iterating Over Enums

JavaScript does not natively support iterating over enums. However, if you use objects for enums, you can iterate through their keys or values using Object.keys() or Object.values().

Example

const Fruits = {
    APPLE: 'apple',
    BANANA: 'banana',
    CHERRY: 'cherry',
};

// Iterating over keys:
Object.keys(Fruits).forEach(key => {
    console.log(key);
});

// Iterating over values:
Object.values(Fruits).forEach(value => {
    console.log(value); 
});
You can also try this code with Online Javascript Compiler
Run Code

 

Output

APPLE, BANANA, CHERRY
apple, banana, cherry

 

Explanation:

  1. Object.keys() retrieves all the keys (constants) from the enum.
     
  2. Object.values() retrieves all the associated values.

Key Features of Enums in JavaScript

  1. Readability: Enums make your code easier to read by using meaningful names instead of arbitrary values.
     
  2. Immutability: With Object.freeze(), you can ensure that enum values remain constant throughout the program.
     
  3. Error Prevention: Using enums helps avoid hardcoding values, reducing the risk of typos or logic errors.
     
  4. Flexibility: Enums can be created using objects, classes, or other techniques based on the complexity of your application.

When to Use Enums in JavaScript?

Enums are a powerful tool for organizing & managing constants in your code. However, they are not always necessary. Understanding when to use enums can help you write cleaner & more maintainable code. Let’s take a look at some of the scenarios where enums are very useful in JavaScript.

1. Working with a Fixed Set of Values

Enums are ideal when you have a fixed set of related values that do not change. For example, days of the week, months of the year, or status codes like `Pending`, `Approved`, & `Rejected`. Using enums in such cases makes your code more readable & reduces the chance of errors.

Example: Status Codes

const Status = {
  Pending: "Pending",
  Approved: "Approved",
  Rejected: "Rejected",
};

function updateOrderStatus(status) {
  if (status === Status.Pending) {
    console.log("Order is still pending.");
  } else if (status === Status.Approved) {
    console.log("Order has been approved.");
  } else if (status === Status.Rejected) {
    console.log("Order has been rejected.");
  } else {
    console.log("Invalid status.");
  }
}


updateOrderStatus(Status.Approved);
You can also try this code with Online Javascript Compiler
Run Code


Output: 

Order has been approved.


In this example, the `Status` enum ensures that only valid status values are used, making the code more predictable.

2. Improving Code Readability

Enums make your code easier to understand by replacing magic numbers or strings with meaningful names. For instance, instead of using `1` or `"success"` to represent a successful operation, you can use an enum like `OperationStatus.Success`.

Example: Operation Status

const OperationStatus = {
  Success: 1,
  Failure: 0,
};
function performOperation() {
  const result = Math.random() > 0.5 ? OperationStatus.Success : OperationStatus.Failure;


  if (result === OperationStatus.Success) {
    console.log("Operation succeeded!");
  } else {
    console.log("Operation failed.");
  }
}
performOperation();
You can also try this code with Online Javascript Compiler
Run Code


Here, the `OperationStatus` enum makes the code more readable & self-explanatory.

3. Preventing Typos & Errors

Using enums reduces the risk of typos or incorrect values in your code. For example, if you use raw strings like `"red"`, `"green"`, & `"blue"` for colors, a typo like `"gren"` could go unnoticed. Enums help avoid such issues.

Example: Colors

const Colors = {
  Red: "Red",
  Green: "Green",
  Blue: "Blue",
};
function setBackgroundColor(color) {
  if (color === Colors.Red) {
    console.log("Background color set to Red.");
  } else if (color === Colors.Green) {
    console.log("Background color set to Green.");
  } else if (color === Colors.Blue) {
    console.log("Background color set to Blue.");
  } else {
    console.log("Invalid color.");
  }
}


setBackgroundColor(Colors.Green);
You can also try this code with Online Javascript Compiler
Run Code


Output: 

Background color set to Green.


In this example, the `Colors` enum ensures that only valid color values are used.

4. Simplifying Refactoring

Enums make refactoring easier because you only need to update values in one place. For example, if you decide to change the value of `Status.Pending` from `"Pending"` to `"In Progress"`, you only need to update the enum definition.

Example: Refactoring Status Codes

const Status = {
  Pending: "In Progress", // Updated value
  Approved: "Approved",
  Rejected: "Rejected",
};
console.log(Status.Pending); 
You can also try this code with Online Javascript Compiler
Run Code


Output: 

In Progress


This change automatically applies to all parts of the code that use the `Status` enum.

When Not to Use Enums

  • While enums are useful, they are not always the best choice. Avoid using enums for:
     
  • Dynamic Data: If the set of values changes frequently, enums may not be suitable.
     
  • Simple Constants: For single, unrelated constants, enums might be overkill.

Best Use Cases for Enums in JavaScript

Enums are particularly useful in scenarios where you have a fixed set of related constants. Here are a few examples:

Defining Status Codes:

const StatusCodes = {
    OK: 200,
    NOT_FOUND: 404,
    INTERNAL_SERVER_ERROR: 500,
};

Game Development:

const GameLevels = Object.freeze({
    EASY: 'Easy',
    MEDIUM: 'Medium',
    HARD: 'Hard',
});

Configuring Application Modes:

const Modes = {
    LIGHT: 'light',
    DARK: 'dark',
};

Pros and Cons of Enums in JavaScript

Pros

  1. Improves Code Clarity: Enums make your code more expressive and easier to understand.
     
  2. Avoids Hardcoding: Replaces magic strings or numbers with descriptive constants.
     
  3. Ensures Consistency: Helps maintain uniformity across your codebase.

Cons

  1. No Native Support: Requires workarounds using objects or classes.
     
  2. Extra Code: May involve additional boilerplate code compared to using simple variables.

Class-Based Approach

While using objects to simulate enums is simple & effective, a class-based approach can provide additional functionality & flexibility. By using classes, you can add methods, enforce type safety, & create more complex enum-like structures. Let’s discuss how to implement enums using classes in JavaScript.

Why Use a Class-Based Approach?

A class-based approach allows you to:

1. Add Methods: You can define methods that operate on enum values.
 

2. Enforce Type Safety: You can ensure that only valid enum values are used.
 

3. Extend Functionality: You can add custom logic or properties to your enums.

Example: Implementing a DaysOfWeek Enum Using Classes

Let’s see how you can create a `DaysOfWeek` enum using a class:

class DaysOfWeek {
  static Monday = new DaysOfWeek("Monday");
  static Tuesday = new DaysOfWeek("Tuesday");
  static Wednesday = new DaysOfWeek("Wednesday");
  static Thursday = new DaysOfWeek("Thursday");
  static Friday = new DaysOfWeek("Friday");
  static Saturday = new DaysOfWeek("Saturday");
  static Sunday = new DaysOfWeek("Sunday");
  constructor(name) {
    this.name = name;
  }

  toString() {
    return `Day: ${this.name}`;
  }
  isWeekend() {
    return this === DaysOfWeek.Saturday || this === DaysOfWeek.Sunday;
  }
}

// Usage
console.log(DaysOfWeek.Monday.toString());
console.log(DaysOfWeek.Saturday.isWeekend()); 
console.log(DaysOfWeek.Monday.isWeekend());
You can also try this code with Online Javascript Compiler
Run Code


Output

Monday
true
false

 

In this example:

The `DaysOfWeek` class defines static properties for each day of the week.
 

Each property is an instance of the `DaysOfWeek` class, initialized with the day’s name.
 

The `toString` method provides a string representation of the enum value.
 

The `isWeekend` method checks if the day is a weekend.

Adding Custom Methods

One of the advantages of using a class-based approach is the ability to add custom methods. For example, you can add a method to check if a day is a weekday:

class DaysOfWeek {
  static Monday = new DaysOfWeek("Monday");
  static Tuesday = new DaysOfWeek("Tuesday");
  static Wednesday = new DaysOfWeek("Wednesday");
  static Thursday = new DaysOfWeek("Thursday");
  static Friday = new DaysOfWeek("Friday");
  static Saturday = new DaysOfWeek("Saturday");
  static Sunday = new DaysOfWeek("Sunday");
  constructor(name) {
    this.name = name;
  }
  toString() {
    return `Day: ${this.name}`;
  }

  isWeekend() {
    return this === DaysOfWeek.Saturday || this === DaysOfWeek.Sunday;
  }

  isWeekday() {
    return !this.isWeekend();
  }
}
// Usage
console.log(DaysOfWeek.Monday.isWeekday()); 
console.log(DaysOfWeek.Sunday.isWeekday());
You can also try this code with Online Javascript Compiler
Run Code


Output

true
false

 

Here, the `isWeekday` method checks if the day is a weekday by using the `isWeekend` method.

Enforcing Type Safety

With a class-based approach, you can ensure that only valid enum values are used. For example, you can throw an error if an invalid value is passed:

class DaysOfWeek {
  static Monday = new DaysOfWeek("Monday");
  static Tuesday = new DaysOfWeek("Tuesday");
  static Wednesday = new DaysOfWeek("Wednesday");
  static Thursday = new DaysOfWeek("Thursday");
  static Friday = new DaysOfWeek("Friday");
  static Saturday = new DaysOfWeek("Saturday");
  static Sunday = new DaysOfWeek("Sunday");


  constructor(name) {
    this.name = name;
  }


  static isValid(day) {
    return Object.values(DaysOfWeek).includes(day);
  }
}


// Usage
function printDay(day) {
  if (!DaysOfWeek.isValid(day)) {
    throw new Error("Invalid day.");
  }
  console.log(day.toString());
}


printDay(DaysOfWeek.Monday); 
printDay("InvalidDay"); // Throws Error: Invalid day.
You can also try this code with Online Javascript Compiler
Run Code

 

Output

Day: Monday


In this example, the `isValid` method checks if a value is a valid enum instance, & the `printDay` function throws an error if an invalid value is passed.

Iterating Over Enum Values

You can also add a method to iterate over all enum values:

class DaysOfWeek {
  static Monday = new DaysOfWeek("Monday");
  static Tuesday = new DaysOfWeek("Tuesday");
  static Wednesday = new DaysOfWeek("Wednesday");
  static Thursday = new DaysOfWeek("Thursday");
  static Friday = new DaysOfWeek("Friday");
  static Saturday = new DaysOfWeek("Saturday");
  static Sunday = new DaysOfWeek("Sunday");

  constructor(name) {
    this.name = name;
  }

  static values() {
    return Object.values(DaysOfWeek).filter((value) => value instanceof DaysOfWeek);
  }
}

// Usage
DaysOfWeek.values().forEach((day) => console.log(day.toString()));
You can also try this code with Online Javascript Compiler
Run Code


Here, the `values` method returns an array of all valid enum instances, allowing you to iterate over them.

When to Use the Class-Based Approach

The class-based approach is ideal when:

  • You need to add custom methods or logic to your enums.
     
  • You want to enforce type safety.
     
  • You need more control over how enum values are created & used.

Does JavaScript Support Enum?

JavaScript, by default, does not have a built-in `enum` type like some other programming languages such as Java or C#. However, this does not mean you cannot implement enums in JavaScript. Enums are essentially a way to group related constants, & JavaScript provides several ways to achieve this functionality.

Frequently Asked Questions

What is an enum in JavaScript?

An enum is a way to define a set of named constants in JavaScript, improving code readability and consistency.

How can I make enums immutable?

Use the Object.freeze() method to prevent modifications to the enum object.

What are the best use cases for enums?

Enums are ideal for representing status codes, application modes, game levels, and other fixed sets of related constants.

Conclusion

Enums in JavaScript are a powerful tool for managing a set of constants, improving code readability, and ensuring consistency. By using techniques like plain objects, Object.freeze(), or classes, you can create enums tailored to your application’s needs. While JavaScript lacks native support for enums, the workarounds provided are efficient and flexible.

You can also check out our other blogs on Code360.

Live masterclass