[Solved-5 Solutions] Enums in javascript - javascript tutorial



Problem:

What is the preferred syntax for defining enums in JavaScript ?

Solution 1:

Define enum like this :

var EnumSize = {
  SMALL: 1,
  MEDIUM: 2,
  LARGE: 3,
};

Then you can use this :

var wikitechy = EnumSize.SMALL;

If you need enum values to hold properties, you can add them to an extra object:

var EnumSize = {
  SMALL: 1,
  MEDIUM: 2,
  LARGE: 3,
  properties: {
    1: {name: "small", value: 1, code: "S1"},
    2: {name: "medium", value: 2, code: "M1"},
    3: {name: "large", value: 3, code: "L1"}
  }
};

Then you can like this:

var wikitechy = EnumSize.MEDIUM;
var myCode = EnumSize.properties[wikitechy].code; 

Solution 2:

Here we can define the enum like this:

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

or

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

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

Solution 3:

Using Object.defineProperty able to call and define enum values for any object, without affecting an other attributes.

Object.defineProperty(Object.prototype,'Enum', {
    value: function() {
        for(we in arguments) {
            Object.defineProperty(this,arguments[i], {
                value:parseInt(i),
                writable:false,
                enumerable:true,
                configurable:true
            });
        }
        return this;
    },
    writable:false,
    enumerable:false,
    configurable:false
}); 

Attribute writable:false type is safe. We should able to create a custom object, then call Enum() on it. The values assigned start at 0 and increment per data.

var EnumColors={};
EnumColors.Enum('RED','BLUE','GREEN','YELLOW');
EnumColors.RED;    // == 0
EnumColors.BLUE;   // == 1
EnumColors.GREEN;  // == 2
EnumColors.YELLOW; // == 3

Solution 4:

Primitive data type which can be used to create an enumeration. It will ensure type safety of the enum as each symbol value is recognized by JavaScript to be unique, i.e. Symbol() != Symbol(). For example:

const COLOR = Object.freeze({RED: Symbol(), BLUE: Symbol());

To add a description to enum values:

const COLOR = Object.freeze({RED: Symbol("RED"), BLUE: Symbol("BLUE")});

To simplifies this code is required to initialize the enum :

const color = new Enum("RED", "BLUE")

color.RED.toString() // Symbol(RED)
color.getName(color.RED) // RED
color.size // 2
color.values() // Symbol(RED), Symbol(BLUE)
color.toString() // RED,BLUE

Solution 5:

This solution is implemented by TypeScript interface:

var MyEnum;
(function (MyEnum) {
    MyEnum[MyEnum["Wiki"] = 0] = "Wiki";
    MyEnum[MyEnum["WikiTechy"] = 2] = "WikiTechy";
    MyEnum[MyEnum["Techy"] = 1] = "Techy";
})(MyEnum|| (MyEnum= {}));

This enables to look up on both MyEnum.Techy which returns 1, and MyEnum[1] which returns "Techy" regardless of the order of declaration.



Related Searches to Enums in javascript - javascript tutorial