How to Use Enums in JavaScript? Defining a Custom Object

If you come from a Typescript background or any other languages like C++, Python, etc., you must have come across Enums. Although “enum” is a reserved keyword in Javascript, Enums don’t really exist in Javascript, but you can “kind of” create them yourself, as you will learn in this post.

An enum is a short form for enumeration. It is a way to define or enumerate all the different choices you may have for a specific thing. It is commonly used when you have something that has a pre-defined set of values. For example, days of the week. They will be the exact same seven days – they will never change.

Enums come in handy when you limit options to certain possible values. This post will give you a comprehensive guide to all the ways you can use to create enums in Javascript.

Define Enums as Object Keys

Assume you have a web application that monitors a student’s online exam. You have created three states for the exam as follows – “Not Started,” Started,” and “Completed.” You can decide to use the code below.

let examState = "Not Started";

//start the exam
examState = "Started";

//finish the exam
examState = "Completed";

This code is okay; however, if you are working with a large application and you have to keep updating the exam state, you might mistype the state, which might break your application.

For example, you might want to verify the exam state, but you make a small typo, as shown below.

if (examState === "Not Started") {
  //code
}

//An error
//Here the word "started" has lowercase 's'
if (examState === "Not started") {
  //code
}

You can use an enum to solve this problem and many others that might arise. The most straightforward method of creating enums in Javascript is by using objects. You encapsulate the enum type and assign a key for each enum value.

For example, you can create an enum to represent the “exam states” above using objects as shown below.

const EXAM_STATE = {
  NOT_STARTED: "NOT Started",
  STARTED: "Started",
  COMPLETED: "Completed",
}

Now, instead of hard-coding your “exam states,” you can read them from the EXAM_STATE enum you just created, as shown below.

//Read exam state
let exam_state = EXAM_STATE.NOT_STARTED

//start the exam (update state)
exam_state=EXAM_STATE.STARTED;

//finish the exam (update state)
exam_state=EXAM_STATE.COMPLETED";

This looks like the perfect solution. Right? Well, No. If you are familiar with updating object properties in Javascript, you know you can mistakenly update the object value, as shown below, which might result in an error.

EXAM_STATE.NOT_STARTED = "Something Else"

EXAM_STATE.STARTED = "Something Else"

EXAM_STATE.COMPLETED = "Something Else"

To prevent such a situation from happening, you will need to use the Object.freeze() method.

Make Enum Objects Immutable with Object.Freeze() Method

In the previous example, you learned that it’s possible to change the value of an enum by updating the object properties. To prevent such from happening, you can use the object.freeze() method, which “freezes” an object. This method makes all object properties non-writable and non-configurable.

Take a look at the code below.

const EXAM_STATE = Object.freeze({
  NOT_STARTED : "NOT Started",
  STARTED : "Started",
  COMPLETED : "Completed",
})

Nothing will happen when you try updating or changing the value of the enum. Take a look at the code below.

EXAM_STATE.NOT_STARTED="not started"
console.log(EXAM_STATE.NOT_STARTED)

/*Output:
NOT Started

From the output above, you can see that the value for the enum did not change. Therefore, always use the “Object.freeze()” method when creating enums in Javascript.

Enums With Symbols

Up to this point, you have learned how to create enums in Javascript and make them immutable. However, there is one problem that you would need to prevent – “overlapping definitions from unrelated enums.”

const DaysOfTheWeek = Object.freeze({
  Sunday: 0,
  Monday: 1,
  Tuesday: 2,
  Wednesday: 3,
  Thursday: 4,
  Friday: 5,
  Saturday: 6,
})

const Mango = Symbol(1);
const Orange = Symbol(2);

//Ideally, this should not be true
console.log(DaysOfTheWeek.Monday === Mango)

/*Output:
true

To avoid conflicts and define values that do not collide with each other, you need to use symbols when creating enums in Javascript. Symbols are always unique and do not equal each other, no matter what. Take a look at the code below.

let symbol1 = Symbol("becomebetterprogrammer");
let symbol2 = Symbol("becomebetterprogrammer");

console.log(symbol1 === symbol2)

/*Output:
false

In the sample code above, the output is “false,” although the two variables “symbol1” and “symbol2” have the same value, “becomebetterprogrammer.” Take a look at the code below.

const Fruits = Object.freeze({
  COLOR_YELLOW: Symbol("mango"),
  COLOR_RED: Symbol("pepper"),
  COLOR_ORANGE: Symbol("orange"),
})

const COLOR_YELLOW = Symbol("mango");
const COLOR_ORANGE = Symbol("orange");

console.log(Fruits.COLOR_YELLOW === COLOR_YELLOW)

/*Output:
false

From the output above, although Fruits.COLOR_YELLOW and COLOR_YELLOW hold the same value, “mango,” they evaluate to “false.” Using symbols when creating enums in Javascript prevents conflicts that might arise due to overlapping definitions.

Note (Important): Unfortunately, Symbols cannot be serialized to JSON. Therefore, if you plan to convert your Enum to a JSON string, use the previous methods described in this post.

Listing All Values of an Enum

Manipulating enums in Javascript is not different from how you would manipulate objects. The code below shows you how you would use the forEach() method to list all possible values of an enum.

const Fruits = Object.freeze({
  COLOR_YELLOW: Symbol("mango"),
  COLOR_RED: Symbol("pepper"),
  COLOR_ORANGE: Symbol("orange"),
})

Object.keys(Fruits).forEach(fruit => console.log(fruit))

/*Output
COLOR_YELLOW
COLOR_RED
COLOR_ORANGE

Conclusion

Although Enums are not yet natively supported in Javascript, you can easily create them using the various methods discussed in this post. Enums always come in handy when working with variables with a fixed or definite number of values.

Was this article helpful? How was your experience working with Enums in Javascript?

Let us know by replying on Twitter of Become A Better Programmer or to my personal Twitter account.