Create enums in JavaScript | Use enums in JavaScript

In computer programming, an enumerated type (also called enumeration, enum, or factor in the R programming language, and a categorical variable in statistics) is a data type consisting of a set of named values called elements, members, enumeral, or enumerators of the type. The enumerator names are usually identifiers that behave as constants in the language.

Wikipedia

An enum is a user-defined type consisting of a set of named constants called enumerators. JavaScript has not any specific enum type. But we can create with help of object.

Example:

Suppose you want to assign integer value to days of week, means whenever any user user any day of week then a assigned integer value should go into database or any where you want to send.

const DaysEnum = {"monday":1, "tuesday":2, "wednesday":3, thrusday:4, friday:5, saturday:6, sunday:7}

Till it also ok, we can use it. But problem with this is any one can change this object with different value, it may cause big problem in code logic.

var day = DaysEnum.monday
console.log(day) // 1

To avoid problem of changing object we can freeze the object itself so that nobody change value accidently.

const DaysEnum = {"monday":1, "tuesday":2, "wednesday":3, thrusday:4, friday:5, saturday:6, sunday:7}
Object.freeze(DaysEnum);

Also Read: DataURL to file in nodejs


After freezing the object, if anyone try to change the value it will be not change.

console.log(DaysEnum.monday) // 1
DaysEnum.monday = 2;
console.log(DaysEnum.monday) // 1
Enums in JavaScript

Leave a Reply