Creating Enums in Vanilla JavaScript

Image from unsplash.comLet’s start with a question: Can numbers represent the types of some subjects? Confusing, right?That’s okay because a number can mean anything that we want, starting from types of cars (say, 1 is for truck) or even the status of …


This content originally appeared on Bits and Pieces - Medium and was authored by Rufat Khaslarov

Image from unsplash.com

Let’s start with a question: Can numbers represent the types of some subjects? Confusing, right?

That’s okay because a number can mean anything that we want, starting from types of cars (say, 1 is for truck) or even the status of a calculation (for instance, 1 is for started).

We might think that just having a variable is enough to understand it. Let’s have a quick look at the code below:

Wow! We can figure out the type of car! But what if we need to add more car types?

We can do this infinitely, and it will still work. These types won’t, however, be logically connected. They’ll be just separate constants that can be moved anywhere in your code. Handling variables this way is a little bit messy.

What are Enums?

With that as our background, let me introduce Enums (the enumeration type). With Enums, a developer can define a set of named constants. This makes it easier to document or create a set of distinct cases.

Using Enums might also mitigate spelling errors, as Enums are unchangeable. And it can make your code safer and cleaner (that is, searchable by name, with the ability to remove the magic values, and so on). Think of Enums as a kind of closed class, the instances of which are predefined statically.

There’s one small problem, though — Enums are not supported in JavaScript natively. However, since Enum is a pattern, it can be replicated via some techniques and features of native JavaScript.

Let’s take a look at two options of applying enumerator in JavaScript.

JavaScript enumeration: a basic representation

Step 1. Define a plain object literal (POJO)

As we mentioned before, Enums are name constants or, in other words, key-value pairs, so we can simply create an object.

The naming convention here is a matter of taste. The most widespread one is PascalCase for name, and UPPER_CASE for keys. But again, it’s up to you to decide how you want it to look.

Note that this still won’t replicate real Enums, because the values can be changed easily.

Step 2. Make sure that values are constant

In native JS, it’s possible to keep properties of the object unchanged. The first option is to use the defineProperty method, but in ES6 we’ve got the freeze method for doing so:

That’s it for basic scenarios. For more complex scenarios, where values should be objects or another logic should be included, we can develop our own Enum implementation.

JavaScript enumerator: an advanced representation

As we know, Enum is a class with predefined instances. So, let’s have a look at our implementation closely. We’ll use ES6, since older versions are not really relevant here:

In this case, we’re literally predefining the instances of the class that can be used in our business logic, and adding the toString method as an example of a custom logic for our enumeration.

We can make this example iterable, add more useful methods, and use the Proxy class for restricting the direct change of the properties, but I’ll leave that for your self-study since it goes beyond the scope of this article.

Other options

You can also use NPM packages like enumify, which helps implement the enum pattern itself, or an enum package that provides complete implementation with more features, like namespaces.

Finally, if you use TypeScript in your project, Enums are available right out of the box.

Summary and useful links

The above explains how we dived into Enums and even created our own customized enumeration in plain JavaScript.

Just a heads-up: you should think carefully before using Enums as they are not uniformly useful in all cases. They can, however, be beneficial in a majority of situations.

Here are some useful links that you might find interesting:

Thanks for reading! I hope you enjoyed this brief tutorial and learned something new about enumeration in JavaScript.

Build with independent components for speed and scale

Instead of building monolithic apps, build independent components first and compose them into features and applications. It makes development faster and helps teams build more consistent and scalable applications.

Bit offers a great developer experience for building independent components and composing applications. Many teams start by building their Design Systems or Micro Frontends, through independent components.
Give it a try →

An independently source-controlled and shared “card” component. On the right => its dependency graph, auto-generated by Bit.

Learn more


Creating Enums in Vanilla JavaScript was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Rufat Khaslarov


Print Share Comment Cite Upload Translate Updates
APA

Rufat Khaslarov | Sciencx (2022-03-07T17:05:04+00:00) Creating Enums in Vanilla JavaScript. Retrieved from https://www.scien.cx/2022/03/07/creating-enums-in-vanilla-javascript/

MLA
" » Creating Enums in Vanilla JavaScript." Rufat Khaslarov | Sciencx - Monday March 7, 2022, https://www.scien.cx/2022/03/07/creating-enums-in-vanilla-javascript/
HARVARD
Rufat Khaslarov | Sciencx Monday March 7, 2022 » Creating Enums in Vanilla JavaScript., viewed ,<https://www.scien.cx/2022/03/07/creating-enums-in-vanilla-javascript/>
VANCOUVER
Rufat Khaslarov | Sciencx - » Creating Enums in Vanilla JavaScript. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/03/07/creating-enums-in-vanilla-javascript/
CHICAGO
" » Creating Enums in Vanilla JavaScript." Rufat Khaslarov | Sciencx - Accessed . https://www.scien.cx/2022/03/07/creating-enums-in-vanilla-javascript/
IEEE
" » Creating Enums in Vanilla JavaScript." Rufat Khaslarov | Sciencx [Online]. Available: https://www.scien.cx/2022/03/07/creating-enums-in-vanilla-javascript/. [Accessed: ]
rf:citation
» Creating Enums in Vanilla JavaScript | Rufat Khaslarov | Sciencx | https://www.scien.cx/2022/03/07/creating-enums-in-vanilla-javascript/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.