Enum definition using Object.freeze

suggest change

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents