Open In App

JavaScript Equivalent to Python Enumerate

Last Updated : 09 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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)

Output
S.p
p
1

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);  

Output
1
2

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)  

Output
Status.p
Status.p

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)); 

Output
1
p

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)  

Output
Cannot 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); 

Output
1

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)

Output
p 1
ip 2
c 3

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]);
}

Output
p 1
ip 2
c 3

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.

Next Article
Article Tags :
Practice Tags :

Similar Reads