Object.defineProperty() Method
You can use the Object.defineProperty() method to define properties that cannot be changed, added, or deleted. You can use this method to create a read-only property for each Enum value. You can use the Object.defineProperty() method to define properties that cannot be changed, added, or deleted. You can use this method to create a read-only property for each Enum value.
Use TypeScript: TypeScript is a superset of JavaScript that includes support for Enums. Using TypeScript, you can define Enums in a way that guarantees their immutability.
Example 1: In this example, we create an Enum object called DaysOfWeek using Object.freeze(). The Object.freeze() method makes the object immutable, so we cannot add, modify or delete properties from the object.
const DaysOfWeek = Object.freeze({
SUNDAY: 0,
MONDAY: 1,
TUESDAY: 2,
WEDNESDAY: 3,
THURSDAY: 4,
FRIDAY: 5,
SATURDAY: 6
});
// Try to modify the enum
// This will not change the Sunday variable
DaysOfWeek.SUNDAY = 7;
console.log(DaysOfWeek.SUNDAY);
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: