Categories
JavaScript Answers

How to Create Enums in JavaScript?

Spread the love

Enums are entities that are containers for a list of constants.

There’s no native enum data type in JavaScript.

However, we can create our own JavaScript enums.

In this article, we’ll take a look at how to create enums with JavaScript.

Create an Object with Symbol Values and Freeze it

To create an enum object in JavaScript, we can create an object with symbol property values.

For instance, we can write:

const Colors = Object.freeze({  
  RED: Symbol("Colors.RED"),  
  BLUE: Symbol("Colors.BLUE"),  
  GREEN: Symbol("Colors.GREEN")  
});  
console.log(Colors.RED)  
console.log(Colors.BLUE)  
console.log(Colors.GREEN)

We create an object with the RED , BLUE and GREEN properties.

Then we set their values to symbols.

Symbols are primitive values that can be used as unique identifiers.

We create a symbol with the Symbol function.

Every symbol created with the Symbol function is unique even if we pass in the same argument to the symbol function, so:

Symbol("Colors.RED") === Symbol("Colors.RED")

is false .

We then call Object.freeze on the object to prevent the object from being frozen.

Once an object is frozen, we can’t add or change existing properties in the object.

Then we can access them like we can do within the console log statements.

Conclusion

We can create enums easily with JavaScript by creating an object with symbol values.

Then we can freeze the object with Object.freeze to prevent changes on the object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *