In JavaScript, enumerators create a set of “constants” or some distinct values, making the code easier to read and maintain. They are also helpful in case of limiting the selection; for instance, the possible values to represent the seasons in temperate climate are Summer, Winter, Autumn, and Spring.
This write-up will discuss the method to create an Enumerator in JavaScript. So, let’s start!
Enumerator in JavaScript
You may know that numbers can be utilized to refer to a “value” and the “type” of something. For instance, in the below-given program, we will associate a number “1” with the constant “SUMMER” as a season type:
Next, we will define a function named “getSeason()” that accepts the “type” as an argument and then compare it with the type of “SUMMER” using strict equality operator “===”:
functiongetSeason(type) {
if (type === SUMMER) {
return{ name: 'Summer Season' };
}
return{ name: 'Other Season' };
}
Lastly, invoke the “getSeason()” function while passing “1” as an argument:
The output of the above-given code will print out the season information on the console, according to the passed type:
Want to define more types of season? To do so, create constants with the name of the specific season and assign a number to it as its “type”:
const SUMMER= 1;
const WINTER= 2;
functiongetSeason(type) {
if (type === SUMMER) {
return{ name: 'Summer Season' };
}
if (type === WINTER) {
return{ name: 'Winter Season' };
}
return{ name: 'Other Season' };
}
getSeason(2);
Output
As you can see from the above-given output, our program is working perfectly. Still, the defined season types are not logically connected and exist as independent constants that can be placed anywhere in the code, making them complex to handle. In such a situation, “Enumerators” comes into play!
Enumerators offer the functionality of defining a set of named “constants” or distinct cases. When this mechanism is utilized, all of the “hard-coded” values are added in a single location to which they are referred, not re-written. Also, the usage of Enumerators also helps in improving the code maintainability.
Now, let’s check out the method of creating Enumerators in JavaScript.
How to create an Enumerator in JavaScript
Enumerators are not supported in ES6 and the prior versions; however, it is a pattern, so we can replicate it using native JavaScript features and techniques.
In JavaScript, you can create Enumerators by:
- Defining an Enumerator “Object”
- Creating an Enumerator “Class”
We will discuss each of the specified methods in the next sections.
How to create Enumerator object in JavaScript
As mentioned earlier, Enumerators are defined as “constants” or “key-value” pairs, so to use them in JavaScript, you have to create an object with the name following “PascalCase” and keys in “Upper_Case”:
SUMMER: 1,
WINTER: 2,
SPRING: 3,
AUTUMN: 4
}
Till this point, we have created an Enumerator named “Seasons,” but its values can be changed easily, which negates it being an Enumerator. We have to specify its properties as “unchangeable” to alter this behavior.
For this purpose, we will invoke the JavaScript “Object.freeze()” method while defining the properties of the “Seasons” object. Upon doing so, the “Object.freeze()” method will freeze the “Seasons” object and prevents its properties from any manipulation:
Output
For basic scenarios, you can create an Enumerator object; however, when you have to specify some logic for adding values, go for the Enumerator Implementation in a JavaScript class.
How to create Enumerator class in JavaScript
To create an “Enumerator” class in JavaScript, follow the below-given instructions:
- First of all, define a “constructor()” for the Enumerator class that accepts a variable number of arguments as “keys”. The created constructor method will be responsible for adding each “key” to an Enumerator object and then freezing it instantly with the help of the “Object.freeze()” method.
- In the next step, utilize the “Symbol.iterator()” method for converting an instance of the Enumerator class into an “iterable” object. This functionality will make the Enumerator object more useful.
- Lastly, declare an object of the “Enumerator” class and pass the “keys” to the constructor().
classEnumerator {
constructor(...keys) {
keys.forEach((key, i) => {
this[key] = i;
});
Object.freeze(this);
}
*[Symbol.iterator]() {
for (let key ofObject.keys(this)) yieldkey;
}
}
constseasonsEnum = newEnumerator(
'summer',
'winter',
'spring',
'autumn');
const seasons= [...seasonsEnum];
console.log(seasons);
Here is how we have implemented the Enumerator class in JavaScript:
We have compiled different methods for creating Enumerators in JavaScript. Depending upon your requirements, you can utilize any of them and benefit from Enumerators’ functionalities.
Conclusion
In JavaScript, you can create an “Enumerator Object” or “Enumerator Class” to implement the concept of Enumeration, where the Enumerator object is used in basic scenarios and the Enumerator class is defined for complex logic. Both approaches utilize the “Object.freeze()” method to freeze the created Enumerator object and mark its properties as unchangeable. This write-up discussed different methods to create an Enumerator in JavaScript.