How to Create Enums in JavaScript ?
Last Updated :
13 Mar, 2024
An enum, short for "enumerated type", is a special data type in programming languages that allows us to define a set of named constants. These constants are essentially unchangeable variables that represent a fixed collection of possible values. Each contants can be accessed by its name. Enums are very similar to constants but they offer more data structure. we will learn about creating enums in JavaScript, exploring their significance in code organization and readability, along with practical implementation approaches using closures and other techniques.
These are the following approaches:
Using Object Literal with Object.freeze()
In this approach, we are using Object.freeze() method. Let's consider the sizes of a T-shirt: Small, Medium, Large and Extra Large. Now let's create an object which represents this available T-shirt sizes and then freeze it using Object.freeze(). This method freezes an object, preventing any additions, deletions, or modifications to its properties.
Example: This example shows the creation of enums using Object.freeze() method.
JavaScript
const TShirtSizes = Object.freeze({
SMALL: 'S',
MEDIUM: 'M',
LARGE: 'L',
EXTRA_LARGE: 'XL'
});
console.log(TShirtSizes.MEDIUM);
Note: If we try to change the TShirtSizes object then it will throw TypeError, because we had enabled Strict mode.
JavaScript
"use strict"; // strict mode is on
const TShirtSizes = Object.freeze({
SMALL: 'S',
MEDIUM: 'M',
LARGE: 'L',
EXTRA_LARGE: 'XL'
});
// Trying to modify a frozen
// object but it will throws an error
TShirtSizes.EXTRA_LARGE = 'XXL';
Output: As demonstrated earlier, attempting to modify the enum after freezing it results in no change, but if strict mode is enabled, it will throw a TypeError.

Note: It's a common convention in many programming languages, including JavaScript, to write enum constants in all capital letters to distinguish them from other variables and constants.
Using ES6 Symbols
- We firstly create an object TShirtSizes
- Inside the object, we define symbols for each size using Symbol()
- The orderTShirt function takes a size argument.
- We had performed a strict comparison (!==) between the argument and each enum member (symbol) to ensure a valid size is provided.
- If a valid size is used, then the order is been processed.
- If anyone attempt to use an invalid string value (e.g. "Medium") throws an error due to the strict comparison with symbols.
Example: This example shows how to create an enum using ES6 Symbols.
JavaScript
const TShirtSizes = {
SMALL: Symbol('Small'),
MEDIUM: Symbol('Medium'),
LARGE: Symbol('Large'),
EXTRA_LARGE: Symbol('Extra Large')
};
function orderTShirt(size) {
if (size !== TShirtSizes.SMALL &&
size !== TShirtSizes.MEDIUM &&
size !== TShirtSizes.LARGE &&
size !== TShirtSizes.EXTRA_LARGE) {
throw new Error('Invalid T-Shirt size!');
}
console.log(`Processing order for
size: ${String(size)}`);
}
orderTShirt(TShirtSizes.MEDIUM);
OutputProcessing order for
size: Symbol(Medium)
Let's see if we try to provide a string argument:
JavaScript
const TShirtSizes = {
SMALL: Symbol('Small'),
MEDIUM: Symbol('Medium'),
LARGE: Symbol('Large'),
EXTRA_LARGE: Symbol('Extra Large')
};
function orderTShirt(size) {
if (size !== TShirtSizes.SMALL &&
size !== TShirtSizes.MEDIUM &&
size !== TShirtSizes.LARGE &&
size !== TShirtSizes.EXTRA_LARGE) {
throw new Error('Invalid T-Shirt size!');
}
console.log(`Processing order for
size: ${String(size)}`);
}
orderTShirt("Medium");
Output:

Using Closures
- Inside the Immediately Invoked Function Expression (IIFE), we define an object Enum containing the enum values.
- We then return the result of calling createEnum(Enum), effectively creating a closure over the Enum object, allowing read-only access to its values through the returned function.
Example: This example shows how to create an enum using Closures.
JavaScript
const Colors = (function () {
const Enum = {
RED: 'RED',
GREEN: 'GREEN',
BLUE: 'BLUE'
};
return (key) => {
return Enum[key];
};
})();
console.log(Colors('RED'));
console.log(Colors('GREEN'));
console.log(Colors('BLUE'));
Note: Attempting to modify the enum directly will result in an error, as the values cannot be modified after the closure is created.
JavaScript
const Colors = (function () {
const Enum = {
RED: 'RED',
GREEN: 'GREEN',
BLUE: 'BLUE'
};
return (key) => {
return Enum[key];
};
})();
// Attempting to modify the enum
// This will throw an Reference error
Colors('RED') = 'YELLOW';
Output: This error occurs when trying to assign a new value to the enum, which is not allowed because the enum is created using closures, providing read-only access to its values.

Similar Reads
How to Create XML in JavaScript ?
In JavaScript, XML documents can be created using various approaches. You can define elements, attributes, and content to structure the XML data, and then serialize it into a string for use or storage. There are several approaches to creating XML in JavaScript which are as follows: Table of Content
2 min read
How to create a JavaScript class in ES6 ?
A class describes the contents of objects belonging to it: it describes a set of data fields (called instance variables) and it defines the operations on those fields (called methods). In order words, it is also defined as the collection or a group of object that contains object data types along wit
2 min read
How to create hash from string in JavaScript ?
To create a unique hash from a specific string, it can be implemented using its own string-to-hash converting function. It will return the hash equivalent of a string. Also, a library named Crypto can be used to generate various types of hashes like SHA1, MD5, SHA256, and many more. These are the fo
3 min read
How to Create JSON String in JavaScript?
JSON strings are widely used for data interchange between a server and a client, or between different parts of a software system. So converting objects to JSON strings is very important for good client-server communication. Below are the following approaches to creating a JSON string: Table of Conte
2 min read
Enums in JavaScript
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 va
4 min read
How to dynamically create new elements in JavaScript ?
New elements can be dynamically created in JavaScript with the help of createElement() method. The attributes of the created element can be set using the setAttribute() method. The examples given below would demonstrate this approach. Example 1: In this example, a newly created element is added as a
4 min read
How to create an element from a string in JavaScript ?
In this article, we will learn how to create an element from a string using JavaScript. This can be used in situations where dynamically generated elements are required by the user. This can be achieved using many approaches as given below: Table of Content Using the createElement() methodUsing the
3 min read
How to Create an Image Element using JavaScript?
We will dynamically create an <img> element in HTML using JavaScript. When a button is clicked, we'll generate the <img> element and append it to the document.Using createElement() methodCreate an empty img element using document.createElement() method.Then set its attributes like (src,
1 min read
How to Create a Nested Object in JavaScript ?
JavaScript allows us to create objects having the properties of the other objects this process is called as nesting of objects. Nesting helps in handling complex data in a much more structured and organized manner by creating a hierarchical structure. These are the different methods to create nested
4 min read
How to Declare an Array in JavaScript?
Array in JavaScript are used to store multiple values in a single variable. It can contain any type of data like - numbers, strings, booleans, objects, etc. There are varous ways to declare arrays in JavaScript, but the simplest and common is Array Litral Notations. Using Array Literal NotationThe b
3 min read