This post will discuss how to create unique and immutable enums using ES6 Symbols in JavaScript.

Symbols are a new primitive data type in ES6 that can be used to create identifiers that are guaranteed to be unique and unchanging. Using ES6 symbols, we can create enums in JavaScript that are unique and immutable. This can be useful for defining a set of constant values that are meaningful and expressive. We can use Symbol() to create a symbol value, and assign it to a property of an object. For instance:

Download  Run Code

 
In this example, we create an object called myEnum that has three properties: FOO, BAR, and BAZ. Each property has a symbol value that is created by passing a string to Symbol(). The string is optional, but it can be useful for debugging purposes. We also use Object.freeze() to prevent any modification to the object or its properties.

Download  Run Code

 
One of the benefits of using symbols as enum values is that they are unique and cannot be duplicated. This means that we can compare them using the strict equality operator (===) without worrying about collisions or type coercion. For example, consider the following code. The symbol value of myEnum.FOO is equal to itself, but not to any other symbol value, even if they have the same string description. This ensures that the enum values are distinct and unambiguous.

Download  Run Code

 
Another benefit of using symbols as enum values is that they are immutable and cannot be changed. This means that we can use them as constants that are safe from mutation or reassignment. Here’s an example:

Download  Run Code

 
As we can see, trying to change the value of myEnum.FOO will fail, because the object is frozen and the property is read-only. This ensures that the enum values are consistent and reliable.

That’s all about creating immutable enums using ES6 Symbols in JavaScript.