JavaScript Equivalent to Python Enumerate
Last Updated :
09 Dec, 2024
Enums in Python are great for defining a set of named values, which makes code more readable and organized. JavaScript doesn't have a built-in enum type, but you can still create something similar. In this article, we'll explore the similarities between Python's Enum and JavaScript's equivalents.
Python (Enum)
In Python, Enum class is part of enum module and is used to define a set of symbolic names bound to unique, constant integer values. We can create enum by subclassing Enum and assigning names and values.
Python
from enum import Enum
class S(Enum):
p = 1 #Pending
ip = 2 #In_progress
c = 3 #Completed
print(S.p)
print(S.p.name)
print(S.p.value)
Explanation:
- The code defines an Enum class S with three members: p, ip, and c, each assigned a unique integer value representing different states (Pending, In Progress, and Completed).
- It prints three different outputs for the S.p enum member: the enum member itself (S.p), its name (S.p.name), and its value (S.p.value), which are displayed as S.p, 'p', and 1 respectively.
JavaScript (Object-based Enum)
The Object.freeze() method is used to prevent modifications to the object, ensuring that values of "enum" cannot be altered which makes it immutable, just like Python's Enum.
JavaScript
const Status = Object.freeze({
p: 1, //Pending
ip: 2, //In_Progress
c: 3 //Completed
});
console.log(Status.p);
console.log(Status.ip);
Explanation:
- The code defines a constant object Status using Object.freeze(), which prevents modification of the object after its creation. This object holds three properties: p, ip, and c, with values representing different statuses (Pending, In Progress, and Completed).
- It prints the values of the Status.p and Status.ip properties, which output 1 (Pending) and 2 (In Progress) respectively.
Let's take a look at some basic comparison of operations between both python's enum and JS equivalent of enum:
Accessing Enum Values
Python (Enum)
Accessing an enum member in Python is straightforward. We can use the name or value of the enum to retrieve its corresponding member.
Python
from enum import Enum
class Status(Enum):
p = 1 #Pending
ip = 2 #In_Progress
c = 3 #Completed
# Accessing by name
status = Status['p']
print(status)
# Accessing by value
status = Status(1)
print(status)
Explanation:
- The code defines an Enum class Status with three members: p, ip, and c, each associated with unique integer values representing different statuses (Pending, In Progress, and Completed). It then demonstrates accessing an enum member by its name (Status['p']), which outputs Status.p.
- It also shows how to access an enum member by its value (Status(1)), which outputs Status.p, as the value 1 corresponds to the p status.
JavaScript (Object-based Enum)
In JavaScript, accessing an enum value is done using object property syntax. However, we cannot directly access an enum member by its value like in Python.
JavaScript
const Status = Object.freeze({
p: 1,
ip: 2,
c: 3
});
// Accessing by name
let status = Status.p;
console.log(status);
function getStatusByValue(value) {
return Object.keys(Status).find(key => Status[key] === value);
}
console.log(getStatusByValue(1));
Explanation:
- The code defines a constant Status object using Object.freeze(), which makes the object immutable. The object has three properties: p, ip, and c, each representing a status with corresponding numeric values.
- It accesses the status by its name (Status.p), which outputs 1 (Pending). The getStatusByValue() function searches through the Status object and returns the name of the status that matches the provided value (1), which outputs 'p'.
Enum Immutability
Python (Enum)
One of the key benefits of using Python's Enum class is that its members are immutable by default. Once created, the values of an enum cannot be changed, which prevents accidental modifications.
Python
from enum import Enum
class Status(Enum):
p = 1 #Pending
ip = 2 #In_Progress
c = 3 #Completed
# Attempting to modify an Enum member raises an error
try:
Status.p = 10
except AttributeError as e:
print(e)
OutputCannot reassign members.
Explanation:
- The code defines an Enum class Status with three members: p, ip, and c, each associated with a unique integer value representing different statuses (Pending, In Progress, and Completed).
- It attempts to modify the value of an enum member (Status.p = 10), but since enum members are immutable, this raises an AttributeError, which is caught by the try-except block, and the error message is printed: 'can't set attribute'.
JavaScript (Object-based Enum)
In JavaScript, we can use Object.freeze() to make an enum object immutable. This prevents adding, deleting, or modifying properties of the object.
JavaScript
const Status = Object.freeze({
p: 1, //Pending
ip: 2, //In Progress
c: 3 //Completed
});
// Attempting to modify an "enum" raises a silent failure (no error)
Status.p = 10;
console.log(Status.p);
Explanation:
- The code defines a constant Status object using Object.freeze(), making the object immutable. The object contains three properties: p, ip, and c, each representing different statuses with numeric values.
- While attempting to modify the value of the Status.p property (Status.p = 10), there is no error, but the modification silently fails because Object.freeze() prevents changes to the object. The console.log(Status.p) will still output the original value 1 (Pending).
Iteration Over Enum Members
Python (Enum)
Python’s Enum class makes it easy to iterate over all the members of an enum.
Python
from enum import Enum
class Status(Enum):
p = 1 #Pending
ip = 2 #In progress
c = 3 #Completed
for status in Status:
print(status.name, status.value)
Explanation:
- The code defines an Enum class Status with three members: p, ip, and c, each associated with a unique integer value representing different statuses (Pending, In Progress, and Completed).
- It iterates over all enum members using a for loop, printing the name and value of each member.
JavaScript (Object-based Enum)
In JavaScript, we can iterate over an object’s keys using for...in or Object.keys() to get the enum names, then access the values.
JavaScript
const Status = Object.freeze({
p: 1, //Pending
ip: 2, //In Progress
c: 3 //Completed
});
for (let key in Status) {
console.log(key, Status[key]);
}
Explanation:
- The code defines a constant Status object using Object.freeze(), making the object immutable. It contains three properties: p, ip, and c, each representing different statuses with corresponding numeric values.
- The for...in loop iterates over the keys (property names) of the Status object, and for each key, it prints the key and its corresponding value.
Similar Reads
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list(). Let's look at a simple exa
3 min read
Python | Counter Objects | elements()
Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python's general-purpose built-ins like dictionaries, lists, and tuples. Counter is a sub-c
6 min read
What Does the Enumerate Function in Python do?
The enumerate function in Python is a built-in function that allows programmers to loop over something and have an automatic counter. It adds a counter to an iterable and returns it as an enumerate object. This feature is particularly useful when you need not only the values from an iterable but als
2 min read
enum.IntEnum in Python
With the help of enum.IntEnum() method, we can get the enumeration based on integer value, if we compare with normal enum based class it will fail by using enum.IntEnum() method. Syntax : enum.IntEnum Return : IntEnum doesn't have a written type. Example #1 : In this example we can see that by using
1 min read
Iterate over a list in Python
Python provides several ways to iterate over list. The simplest and the most common way to iterate over a list is to use a for loop. This method allows us to access each element in the list directly. Example: Print all elements in the list one by one using for loop. [GFGTABS] Python a = [1, 3, 5, 7,
3 min read
Java Collections emptyEnumeration()â Method with Examples
The emptyEnumeration() method of Java Collections is used to get the empty enumeration that contains no elements in Java. Syntax: public static <T> Enumeration<T> emptyEnumeration() Parameters: This method has no parameters. Return Type: This method will return an empty enumeration. Exce
2 min read
enum in Python
Enumerations in Python are implemented by using the module named "enum". Enumerations are created using classes. Enums have names and values associated with them. Let's cover the different concepts of Python Enum in this article.What are Enums and Why are they useful?Enumerations or Enums is a set o
6 min read
Automate getter-setter generator for Java using Python
Encapsulation is defined as the wrapping up of data under a single unit. Encapsulation can be achieved by declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables. These public methods are called getters and setters. In practi
3 min read
Convert List of Characters to String in Java
Given a list of characters. In this article, we will write a Java program to convert the given list to a string. Example of List-to-String ConversionInput : list = {'g', 'e', 'e', 'k', 's'} Output : "geeks" Input : list = {'a', 'b', 'c'} Output : "abc" Strings - Strings in Java are objects that are
4 min read
Python | Consecutive remaining elements in list
Sometimes, while working with Python list, we can have a problem in which we need to get the consecutive elements count remaining( including current ), to make certain decisions beforehand. This can be a potential subproblem of many competitive programming competitions. Let's discuss a shorthand whi
2 min read