HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How can I guarantee that my enums definition doesn't change in JavaScript?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howenumsdefinitiondoesnchangecanthatguaranteejavascript

Problem

Would the following make the objects fulfil all characteristics that enums have in JavaScript? Something like:
my.namespace.ColorEnum = {
RED : 0,
GREEN : 1,
BLUE : 2
}

// later on

if(currentColor == my.namespace.ColorEnum.RED) {
// whatever
}



Or is there some other way I can do this?

Solution

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

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


or

const 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


One way to ensure a stronger degree of type safety (with enums or otherwise) is to use a tool like TypeScript or Flow.

Quotes aren't needed but I kept them for consistency.

Code Snippets

const DaysEnum = Object.freeze({"monday":1, "tuesday":2, "wednesday":3, ...})
const DaysEnum = {"monday":1, "tuesday":2, "wednesday":3, ...}
Object.freeze(DaysEnum)
let day = DaysEnum.tuesday
day = 298832342 // goes through without any errors

Context

Stack Overflow Q#287903, score: 1201

Revisions (0)

No revisions yet.