Tutorial by Examples

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; // Prin...
The Object.freeze() method is available since version 5.1. For older versions, you can use the following code (note that it also works in versions 5.1 and later): var ColorsEnum = { WHITE: 0, GRAY: 1, BLACK: 2 } // Define a variable with a value from the enum var currentColor = Co...
After defining an enum using any of the above ways and setting a variable, you can print both the variable's value as well as the corresponding name from the enum for the value. Here's an example: // Define the enum var ColorsEnum = { WHITE: 0, GRAY: 1, BLACK: 2 } Object.freeze(ColorsEnum); // D...
As ES6 introduced Symbols, which are both unique and immutable primitive values that may be used as the key of an Object property, instead of using strings as possible values for an enum, it's possible to use symbols. // Simple symbol const newSymbol = Symbol(); typeof newSymbol === 'symbol' // t...
5.1 This Example demonstrates how to automatically assign a value to each entry in an enum list. This will prevent two enums from having the same value by mistake. NOTE: Object.freeze browser support var testEnum = function() { // Initializes the enumerations var enumList = [ &q...

Page 1 of 1