How to use a Closure In Javascript
You can also use a closure to create an Enum. A closure is a function that has access to variables in its outer function scope. By creating an inner function that returns a value, we can make the variable in the outer function scope read-only.
Example: In this example, we use a closure to create an object called DaysOfWeek. The days object is defined in the outer function scope and is not accessible from outside the function. The inner function get returns the value of the property with the given name from the days object. Since the days object is not directly accessible, it cannot be modified from outside the closure.
const DaysOfWeek = (function () {
const days = {
SUNDAY: 0,
MONDAY: 1,
TUESDAY: 2,
WEDNESDAY: 3,
THURSDAY: 4,
FRIDAY: 5,
SATURDAY: 6
};
return {
get: function (name) {
return days[name];
}
};
})();
// Try to modify the enum
// This will not have any effect
DaysOfWeek.SUNDAY = 7;
console.log(DaysOfWeek.get('SUNDAY')); // Output: 0
Output:
0
Enums in JavaScript
Enums in JavaScript are a way to define a set of named constants, often used to represent a collection of related values. While JavaScript doesn’t have built-in support for enums, similar functionality can be achieved using objects or const variables to improve code readability and maintainability.
In JavaScript, Enumerations or Enums are used to represent a fixed set of named values. However, Enums are not native to JavaScript, so they are usually implemented using objects or frozen arrays.
To ensure the immutability of Enums in JavaScript, you can follow these guidelines: