Loading lesson path
An enum is a special "class" that represents a group of constants (unchangeable variables). Enums come in two flavors string and numeric. Let's start with numeric.
Formula
Numeric Enums - DefaultBy default, enums will initialize the first value to
and add 1 to each additional value:
Example enum CardinalDirections {North, East, South,
}
let currentDirection = CardinalDirections.North;
// logs 0 console.log(currentDirection);
// throws error as 'North' is not a valid enum currentDirection = 'North'; // Error: "North" is not assignable to type 'CardinalDirections'.Formula
Numeric Enums - InitializedYou can set the value of the first numeric enum and have it auto increment from that:
Example enum CardinalDirections {Formula
North = 1,East, South,
}
// logs 1 console.log(CardinalDirections.North);
// logs 4 console.log(CardinalDirections.West);Formula
Numeric Enums - Fully InitializedYou can assign unique number values for each enum value. Then the values will not be incremented automatically:
Example enum StatusCodes {Formula
NotFound = 404,
Success = 200,
Accepted = 202,
BadRequest = 400}
// logs 404 console.log(StatusCodes.NotFound);
// logs 200 console.log(StatusCodes.Success);Enums can also contain strings. This is more common than numeric enums, because of their readability and intent.
Example enum CardinalDirections {
North = 'North',
East = "East",
South = "South",
West = "West"
};
// logs "North"
console.log(CardinalDirections.North);
// logs "West"
console.log(CardinalDirections.West);Technically, you can mix and match string and numeric enum values, but it is recommended not to do so.