How to Create and Use Enums in JavaScript
Table of Contents
Enums are a useful way to define a set of named constants.
While very popular and ubiquitous in other languages, JavaScript does not have a native enum type. However, it is possible to emulate enums in JavaScript using objects.
In this post, we'll learn how to create and use enums in JavaScript.
How to create enums in JavaScript
To create an enum in JavaScript, we can use an object. The object's keys will be the enum's values, and the object's values will be the enum's keys.
Let's look an example:
JAVASCRIPTconst compass = {
NORTH: "NORTH",
SOUTH: "SOUTH",
EAST: "EAST",
WEST: "WEST"
};
In the above example, we created an enum called compass
with four values: NORTH
, SOUTH
, EAST
, and WEST
.
This does a pretty good job of somewhat emulating what an enum is in other languages.
For example, you can get all the values of the enum by using Object.values()
:
JAVASCRIPTObject.values(compass); // ["NORTH", "SOUTH", "EAST", "WEST"]
You can check if a value is part of the enum by using Object.values()
:
JAVASCRIPTObject.values(compass).includes("NORTH"); // true
You can also check if a value is equal to a specific enum value:
JAVASCRIPTcompass.NORTH === "NORTH"; // true
However, one major drawback of this approach is that you can edit the enum at anytime, thanks to JavaScript"s dynamic nature:
JAVASCRIPTcompass.NORTH = "SOUTH";
compass.NORTH; // "SOUTH"
To get around this, we can use Object.freeze()
to make the enum immutable:
JAVASCRIPTconst compass = Object.freeze({
NORTH: "NORTH",
SOUTH: "SOUTH",
EAST: "EAST",
WEST: "WEST"
});
Now, if you try to edit the enum, you'll get an error:
JAVASCRIPTcompass.NORTH = "SOUTH"; // TypeError: Cannot assign to read only property 'NORTH' of object '#<Object>'
Conclusion
In this post, we learned how to create and use enums in JavaScript.
Simply wrap an object in Object.freeze()
to make it immutable and it is about the closest thing we have in JavaScript to a fully-fledged enum.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Svelte
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- How to deploy a Deno app using Docker
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Using Push.js to Display Web Browser Notifications
- Setting Up Stylus CSS Preprocessor
- Getting Started with Vuex: Managing State in Vue
- How To Create a Modal Popup Box with CSS and JavaScript