JavaScript Enumerations Enum definition using Object.freeze()

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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.



Got any JavaScript Question?