ES6 Symbol
Another approach to creating an Enum in JavaScript is to use ES6 Symbols. Symbols are unique identifiers that cannot be duplicated and can be used to define constant values that are guaranteed to be unique and unchanging.
Example: In this example, we’re defining an enum called myEnum using Object.freeze() to prevent any modifications to the object. We’re using Symbol() to create unique symbols for each enum value.
const myEnum = Object.freeze({
FOO: Symbol('foo'),
BAR: Symbol('bar'),
BAZ: Symbol('baz')
});
console.log(myEnum.FOO); // Symbol(foo)
// Attempting to modify the enum
// values will have no effect
myEnum.FOO = Symbol('newFoo');
console.log(myEnum.FOO); // Symbol(foo)
// Adding a new property to the enum
// object will also have no effect
myEnum.QUX = Symbol('qux');
console.log(myEnum.QUX); // undefined
Output:
Symbol(foo)
Symbol(foo)
undefined
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: