Enumerations in Javascript

April 15, 2021


How to define enums in Javascipt

Enumerations offer an easy way to work with sets of related constants.An enumeration, or Enum , is a symbolic name for a set of values. Enumerations are treated as data types, and you can use them to create sets of constants for use with variables and properties.

Natively javascript doesn't support enums but still you can implement enum in javascipt. One of the available ways is to defining an object and then freezing it after definition.A frozen object can not be modified or you can not add other properties after definition and it's values can not be changed/modified. This keeps the enumeration idea

Syntax to create an enum in javascipt

 const daysEnum = {
      MON:1,
      TUE:2,
      WED:3,
      THUR:4,
      FRI:5,
      SAT:6
      SUN:7
    };

 Object.freeze(daysEnum);

How to access values

To be able to access 7 as the seventh day of the week using our difined enum, here is the syntax

let value = daysEnum.SUN; // 7
Hope that was helpful

#javascript #enum