Skip to content

Commit 3b20ff0

Browse files
authored
[Edit] JavaScript: Enums (#6546)
* [Edit] JavaScript: Enums * Update content/javascript/concepts/enums/enums.md * Update content/javascript/concepts/enums/enums.md * Made suggested changes ---------
1 parent 89bdb4d commit 3b20ff0

File tree

1 file changed

+110
-39
lines changed
  • content/javascript/concepts/enums

1 file changed

+110
-39
lines changed
Lines changed: 110 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,80 +1,151 @@
11
---
22
Title: 'Enums'
3-
Description: 'JavaScript has no support for a native enum type, but it is possible to define enums using Objects.'
3+
Description: 'Enums are a data type that can hold a finite number of defined immutable values.'
44
Subjects:
5-
- 'Web Development'
65
- 'Computer Science'
6+
- 'Web Development'
77
Tags:
88
- 'Arrays'
99
- 'Data Types'
10+
- 'Enum'
11+
- 'JavaScript'
1012
CatalogContent:
1113
- 'introduction-to-javascript'
1214
- 'paths/front-end-engineer-career-path'
1315
---
1416

15-
JavaScript has no support for a native **enum** type, but it is possible to define enums using `Object`s. In general, enums are a type that can hold a finite number of defined values. The values in enums are not mutable.
17+
In general, **enums** are a data type that can hold a finite number of defined values. The values in enums are not mutable. Though JavaScript has no support for a native enum type, it is possible to define enums using various approaches. These approaches make the code more expressive, self-documenting, and less error-prone.
18+
19+
## Implementing JavaScript Enums
1620

17-
## Implementing an Enum in JavaScript
21+
There are three ways to implement enums in JavaScript:
1822

19-
A way to implement an enum in JavaScript by creating an `Object` of key/value pairs and using the `Object.freeze()` function to make it immutable:
23+
- Using plain objects
24+
- Using `Object.freeze()`
25+
- Using Symbols
26+
27+
### Using Plain Objects
28+
29+
The simplest way to create JavaScript enums is by using plain objects:
2030

21-
<!-- prettier-ignore-start -->
2231
```js
23-
const directions = Object.freeze({
24-
north: 0,
25-
south: 1,
26-
east: 2,
27-
west: 3
32+
const directions = {
33+
NORTH: 0,
34+
SOUTH: 1,
35+
EAST: 2,
36+
WEST: 3,
37+
};
38+
```
39+
40+
The enum can then be used as follows:
41+
42+
```js
43+
let direction = directions.NORTH;
44+
```
45+
46+
This approach is straightforward and works well for most use cases, but the values can still be modified unless it is explicitly prevented.
47+
48+
### Using `Object.freeze()`
49+
50+
The `Object.freeze()` method is used to create an immutable JavaScript enum:
51+
52+
```js
53+
const directions = Object.freeze({
54+
NORTH: 0,
55+
SOUTH: 1,
56+
EAST: 2,
57+
WEST: 3,
2858
});
2959
```
30-
<!-- prettier-ignore-end -->
3160

32-
The enum can be used as follows:
61+
This approach ensures that the object and its values cannot be changed, providing a more robust and predictable enum.
62+
63+
### Using Symbols
64+
65+
Symbols are used to create truly unique enum values that are not prone to accidental collisions:
3366

3467
```js
35-
let d = directions.north;
68+
const directions = {
69+
NORTH: Symbol(0),
70+
SOUTH: Symbol(1),
71+
EAST: Symbol(2),
72+
WEST: Symbol(3),
73+
};
3674
```
3775

38-
All possible enum values can be listed as follows:
76+
This approach guarantees uniqueness and is ideal when there is a need to create enum values that should not clash or be compared to other values carelessly.
77+
78+
## Example 1: Traffic Light Management
79+
80+
This example uses JavaScript enums to display the current traffic light:
3981

4082
```js
41-
Object.keys(directions).forEach((direction) =>
42-
console.log('direction:', direction)
43-
);
83+
const TrafficLight = Object.freeze({
84+
RED: 'RED',
85+
YELLOW: 'YELLOW',
86+
GREEN: 'GREEN',
87+
});
88+
89+
const currentTrafficLight = TrafficLight.GREEN;
90+
91+
console.log(currentTrafficLight);
92+
```
93+
94+
The output for the example will be:
95+
96+
```shell
97+
GREEN
98+
```
99+
100+
## Example 2: Order Status Handling
101+
102+
This example uses JavaScript enums to display the order status:
103+
104+
```js
105+
const StatusOptions = Object.freeze({
106+
PENDING: 'PENDING',
107+
SHIPPED: 'SHIPPED',
108+
DELIVERED: 'DELIVERED',
109+
CANCELED: 'CANCELED',
110+
});
111+
112+
const orderStatus = StatusOptions.DELIVERED;
113+
114+
console.log(orderStatus);
44115
```
45116

46-
This would produce the output:
117+
The output for the example will be:
47118

48119
```shell
49-
direction: north
50-
direction: south
51-
direction: east
52-
direction: west
120+
DELIVERED
53121
```
54122

55-
## Codebyte Example
123+
## Codebyte Example: Role-Based Access Control
56124

57-
This codebyte example demonstrates the creation of an `enum` using `Object.freeze()`, how to use the enum values, and list all possible enum values:
125+
This codebyte example uses JavaScript enums to display the access level based on the user role:
58126

59127
```codebyte/javascript
60128
const UserRoles = Object.freeze({
61-
ADMIN: 'admin',
62-
EDITOR: 'editor',
63-
VIEWER: 'viewer'
129+
ADMIN: 'ADMIN',
130+
EDITOR: 'EDITOR',
131+
VIEWER: 'VIEWER'
64132
});
65133
66-
let userRole = UserRoles.ADMIN;
134+
const userRole = UserRoles.ADMIN;
135+
67136
console.log(userRole);
137+
```
68138

69-
function canEdit(userRole) {
70-
return userRole === UserRoles.ADMIN || userRole === UserRoles.EDITOR;
71-
}
139+
## Frequently Asked Questions
72140

73-
console.log(canEdit(UserRoles.ADMIN));
74-
console.log(canEdit(UserRoles.EDITOR));
75-
console.log(canEdit(UserRoles.VIEWER));
141+
### 1. Can enums be iterated in JavaScript?
76142

77-
Object.keys(UserRoles).forEach((role) =>
78-
console.log('role:', role)
79-
);
80-
```
143+
Yes. If you use plain objects, you can iterate enums using `Object.keys()` or `Object.values()`. However, enums using Symbols cannot be easily iterated since Symbols are not enumerable by default.
144+
145+
### 2. Are JavaScript enums good for performance?
146+
147+
JavaScript enums generally have negligible performance overhead. In fact, they can improve performance indirectly by reducing bugs and logical errors in your code.
148+
149+
### 3. When should I avoid using enums in JavaScript?
150+
151+
Avoid enums when your values are unlikely to repeat or belong to a limited set. In such cases, using simple variables or constants might be more appropriate. Also, overusing enums for trivial values can make code unnecessarily complex.

0 commit comments

Comments
 (0)