What is an Enum?
An enum is an object which has a collection of related values stored together. Javascript does not support enums. Most of the programming language like java, c, c++ supports enum and it also available with typescript too. Enums are defined using keyword enum.
How to declare an Enum?
Syntax:
enum NameofEnum {
value1,
value2,
..
}
Example: Enum
enum Directions {
North,
South,
East,
West
}
In the above example, you have defined an enum called Directions. The value given is North, South, East, West. The values are numbered from 0 for the first value in the enum and subsequently increments by 1 for the next value.
Declare An Enum with a numeric value
By default, if an enum is not given any value, it considers it a number starting from 0. Following example shows an enum with a numeric value.
enum Directions {
North = 0,
South = 1,
East =2,
West =3
}
You may also assign a start value to the enum and the next enum values will get the incremented values. For example:
enum Directions {
North = 5,
South, // will be 6
East, // 7
West // 8
}
Now the enum value North starts with 5, so South will get value as 6, East = 7 and West = 8.
You may also assign values of your choice instead of taking the default ones. For Example:
enum Directions {
North = 5,
South = 4,
East = 6,
West = 8
}
How to access an Enum?
Following example shows how to make use of Enum in your code:
enum Directions {
North,
South,
East,
West
}
console.log(Directions.North); // output is 0
console.log(Directions["North"]); // output is 0
console.log(Directions[0]); //output is North
The compiled code to javascript is as follows:
var Directions;
(function (Directions) {
Directions[Directions["North"] = 0] = "North";
Directions[Directions["South"] = 1] = "South";
Directions[Directions["East"] = 2] = "East";
Directions[Directions["West"] = 3] = "West";
})(Directions || (Directions = {}));
console.log(Directions.North);
console.log(Directions["North"]);
console.log(Directions[0]);
Since Javascript does not support enums, it converts the enum into a self invoked functions as shown above.
Declare An Enum with a string value
You can assign string values of your choice, as shown in the example below:
Example:
enum Directions {
North = "N",
South = "S",
East = "E",
West = "W"
}
console.log(Directions.North); // output is N
console.log(Directions["North"]); // output is N
console.log(Directions[0]); // output is North
The compiled code to javascript is as follows:
var Directions;
(function (Directions) {
Directions["North"] = "N";
Directions["South"] = "S";
Directions["East"] = "E";
Directions["West"] = "W";
})(Directions || (Directions = {}));
console.log(Directions.North);
console.log(Directions["North"]);
console.log(Directions[0]);