enum Direction {
Up = 1,
Down,
Left,
Right
}
console.log(Direction.Up);
console.log(Direction[2]);The enum Direction starts with Up = 1. The next members auto-increment, so Down is 2, Left is 3, and Right is 4.
Accessing Direction.Up prints 1. Accessing Direction[2] returns the name of the member with value 2, which is 'Down'.
Enums help group related named values together, making code easier to read and maintain. They also provide automatic numbering and reverse mapping.
They do not affect runtime speed or variable declaration rules.
enum Status {
Active = 'ACTIVE',
Inactive = 'INACTIVE',
Pending
}
console.log(Status.Pending);When an enum member is assigned a string value, all following members must also have initializers. Here, Pending has no value, causing a compile error.
enum Colors {
Red,
Green,
Blue
}Numeric enums create both forward (name to value) and reverse (value to name) mappings. For 3 members, there are 6 keys total.
enum Mixed {
A = 1,
B = 'B',
C = 3
}
console.log(Mixed.A);
console.log(Mixed.B);
console.log(Mixed.C);
console.log(Mixed['B']);The mixed enum compiles successfully. Mixed.A is 1 (with reverse Mixed[1] = 'A'), Mixed.B is 'B' (no reverse mapping Mixed['B'] = 'B' created), Mixed.C is 3 (with reverse Mixed[3] = 'C'). However, Mixed['B'] accesses the forward mapping property 'B', which holds 'B'. Outputs: 1, 'B', 3, 'B'.