What is the preferred syntax for defining enums in JavaScript?

Technology CommunityCategory: JavaScriptWhat is the preferred syntax for defining enums in JavaScript?
VietMX Staff asked 4 years ago

Since 1.8.5 it’s possible to seal and freeze the object, so define the above as:

var DaysEnum = Object.freeze({
    "monday": 1,
    "tuesday": 2,
    "wednesday": 3,
    ...
})

or

var DaysEnum = {
    "monday": 1,
    "tuesday": 2,
    "wednesday": 3,
    ...
}
Object.freeze(DaysEnum)

and voila! JS enums.

However, this doesn’t prevent you from assigning an undesired value to a variable, which is often the main goal of enums:

let day = DaysEnum.tuesday
day = 298832342 // goes through without any errors