If you’re coming from a TypeScript background or have experience with languages like C++ or Python, you’re probably familiar with Enums.Enums, short for enumerations, are a way to define or enumerate all the different choices you may have for a specific thing.
While JavaScript doesn’t have native Enums like some other languages, you can create your own custom Enums. In this article, we’ll explore how to define Enums in JavaScript and ensure their immutability.
What are Enums?
Enums are essential when you want to restrict the possible values a variable can hold. For instance, think of the days of the week; they are always the same seven days and never change.
Enums provide a way to represent such fixed sets of values.
Define Enums as Object Keys
Imagine you’re building a web application to monitor a student’s online exam. You’ve defined three states for the exam: “Not Started,” “Started,” and “Completed.”
Instead of using simple string variables that might lead to typos and errors, you can create an Enum object to represent these states:
const EXAM_STATE = {
NOT_STARTED: "Not Started",
STARTED: "Started",
COMPLETED: "Completed",
}
With this approach, you can access the states using the Enum:
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;
However, there’s a downside. You can accidentally update the Enum values like this:
EXAM_STATE.NOT_STARTED = "Something Else"; // This is problematic
Make Enum Objects Immutable with Object.freeze() Method
To prevent unintentional changes to Enum values, you can use the Object.freeze() method:
const EXAM_STATE = Object.freeze({
NOT_STARTED: "Not Started",
STARTED: "Started",
COMPLETED: "Completed",
})
Now, any attempt to modify the Enum values will result in an error. It ensures the Enum remains immutable and reliable.
EXAM_STATE.NOT_STARTED = "not started"; // No effect, it remains "Not Started"
Enums With Symbols
In some cases, you might want to ensure that Enum values don’t accidentally overlap with other values. Symbols are unique and can help you achieve this:
const DaysOfTheWeek = Object.freeze({
Sunday: Symbol(1),
Monday: Symbol(2),
Tuesday: Symbol(3),
Wednesday: Symbol(4),
Thursday: Symbol(5),
Friday: Symbol(6),
Saturday: Symbol(7),
})
Using Symbols makes it less likely for values to conflict:
const Mango = Symbol("mango");
const Orange = Symbol("orange");
console.log(DaysOfTheWeek.Monday === Mango); // Output: false
Here is another interesting article: Double exclamation marks in JS why we use them
Listing All Values of an Enum
You can manipulate Enums in JavaScript just like regular objects. To list all possible values of an Enum, you can use the Object.keys() method:
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
Here is another interesting article: How much JavaScript is required to start a career in software development?”
Conclusion
Although JavaScript doesn’t natively support Enums, you can easily create them using the methods discussed in this article. Enums are invaluable when dealing with variables that should only have a predefined set of values.
By encapsulating these values in Enum objects and ensuring their immutability, you can write more robust and error-resistant code.
In your journey with Enums in JavaScript, consider the use of Symbols to prevent value conflicts, especially when you need uniqueness.
Now that you have a comprehensive guide on working with Enums, you can apply these concepts to enhance your JavaScript coding practices.
People also love to read another interesting article about Camel Case and Snake Case.
Leave a Reply