Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an enum in JavaScript [duplicate]

Tags:

javascript

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?

like image 835
David Citron Avatar asked Nov 13 '08 19:11

David Citron


People also ask

Can enum have duplicate values?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

How do you declare an enum in JavaScript?

The easiest way to define an enum would be to use Object. freeze() in combination with a plain object. This will ensure that the enum object cannot be mutated. const daysEnum = Object.

Can two enums have the same name?

No two enum members can have the same name. Each enum member has an associated constant value.

How does enum work JavaScript?

Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.


1 Answers

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.

like image 113
Artur Czajka Avatar answered Oct 08 '22 07:10

Artur Czajka