Enums in JavaScript

Mateusz -

Enum – Enumerated Type which allows us to store series of values, a fixed set of constants.

When to use it?

When your variable can be one of the chosen values from defined series of values. For example you can define enum for colours like RED, PINK, and WHITE. Or you can define enum for continents like EUROPE, ASIA, and AUSTRALIA or enum for messages: SUCCESS, ERROR, and WARNING.

Enum creation using an object

We can easily create enums using an object-oriented approach.

//
const notifications = {
   SUCCESS: 'Everything is good',
   ERROR: 'Something went wrong',
   WARNING: 'Be careful'
};

notifications.SUCCESS //Everything is good
notifications.ERROR //Something went wrong
notifications.WARNING //Be careful
//

Other examples

//
const compassDirections = {
   NORTH: 'north',
   SOUTH: 'south',
   WEST: 'west',
   EAST: 'east'
};

const sizes = {
   SMALL: 's',
   MEDIUM: 'm',
   LARGE: 'l'
};
//

Here is our enum. Created in JavaScript nice and running. But there is one problem with that. Enums editing should be blocked. It should have a fixed set of constants. Since notifications are a const we cannot change their value. But const does not block us from changing the value of the object.

//
notifications = ''; //Error! Assignment to constant variable.

//This should work...
notifications.SUCCESS = 'New notification message';

notifications.SUCCESS; //New notification message
//

Now we have a problem. SUCCESS value is changed and our enum is edited. Of course we are to blame for that because we changed it, but the enum should always be read-only, for safety reasons and good coding practice.

Enum creation using Object.freeze() method

Object.freeze will solve our problem above. We will “freeze” our enum, our object, so that it will be blocked from editing and will make the properties of the object non-writable and non-configurable.

//
const notifications = Object.freeze({
   SUCCESS: 'Everything is good',
   ERROR: 'Something went wrong',
   WARNING: 'Be careful'
});

notifications.SUCCESS; //Everything is good
notifications.ERROR; //Something went wrong
notifications.WARNING; //Be careful
//

//And now this should do nothing
notifications.SUCCESS = 'New notification message';

notifications.SUCCESS; //Everything is good
//

Summary

Enums are cool. They provide us with a good way to store series of values. When we choose to use enum, it is good to remember to use Object.freeze() method to ensure that your enum will always be read-only.