Enums
ℹ️ Used as a collection of related values. Use enums when a method or variable can only take one out of a small set of possible values.
An enum is a way to organize a collection of related values.
1
enum Seasons {
2
Summer,
3
Autumn,
4
Winter,
5
Spring,
6
}
Copied!
These enums values are number-based:
1
const summer = Seasons.Summer;
2
console.log(summer);
3
// -> 0
Copied!
Direction.Up is 0, Direction.Down is 1 and so on...
Now, let's look at the JavaScript that it generates:
1
var Seasons;
2
(function(Seasons) {
3
Seasons[(Seasons['Summer'] = 0)] = 'Summer';
4
Seasons[(Seasons['Autumn'] = 1)] = 'Autumn';
5
Seasons[(Seasons['Winter'] = 2)] = 'Winter';
6
Seasons[(Seasons['Spring'] = 3)] = 'Spring';
7
})(Seasons || (Seasons = {}));
Copied!
Let's take the line Seasons[Seasons["Summer"] = 0] = "Summer";. To understand this line we just need to analyze Seasons["Summer"] = 0, here we can see that it assigns value 0 to the Seasons.Summer, then we know that assignment operator returns the assigned value, so further execution is Seasons[0] = "Summer".
1
console.log(Seasons.Summer); // 0
2
console.log(Seasons[0]); // "Summer"
Copied!
Enums have autoincrementing behavior:
1
enum Seasons {
2
Summer = 1,
3
Autumn,
4
Winter,
5
Spring,
6
}
Copied!
When Up is initilized with 1, others have auto-incremented value from that point. Direction.Down has value 2, Direction.Left has 3, Direction.Right has 4.
String Enums
1
enum Seasons {
2
Summer = 'SUMMER',
3
Autumn = 'AUTUMN',
4
Winter = 'WINTER',
5
Spring = 'SPRING',
6
}
Copied!
String enums don't have auto-increment behavior. It's required to give assign a value to each enum member.
Generated code is the following:
1
var Season;
2
(function(Season) {
3
Season['Summer'] = 'SUMMER';
4
Season['Autumn'] = 'AUTUMN';
5
Season['Winter'] = 'WINTER';
6
Season['Spring'] = 'SPRING';
7
})(Season || (Season = {}));
Copied!
So
1
console.log(Season.Summer); // -> "SUMMER"
2
console.log(Season[0]); // -> undefined
Copied!

Read More

Copy link
Contents
Read More