JavaScript Enum definition using Object.freeze()


Example

5.1

JavaScript does not directly support enumerators but the functionality of an enum can be mimicked.

// Prevent the enum from being changed
const TestEnum = Object.freeze({
    One:1,
    Two:2,
    Three:3
});
// Define a variable with a value from the enum
var x = TestEnum.Two;
// Prints a value according to the variable's enum value
switch(x) {
    case TestEnum.One:
        console.log("111");
        break;

    case TestEnum.Two:
        console.log("222");
}

The above enumeration definition, can also be written as follows:

var TestEnum = { One: 1, Two: 2, Three: 3 }
Object.freeze(TestEnum);

After that you can define a variable and print like before.