9.2 Enum Members

The body of an enum declaration defines zero or more enum members which are the named values of the enum type. Each enum member has an associated numeric value of the primitive type introduced by the enum declaration.

  EnumBody:   EnumMemberList,opt

  EnumMemberList:   EnumMember   EnumMemberList,EnumMember

  EnumMember:   PropertyName   PropertyName = EnumValue

  EnumValue:   AssignmentExpression

The PropertyName of an enum member cannot be a computed property name (2.2.3).

Enum members are either constant members or computed members. Constant members have known constant values that are substituted in place of references to the members in the generated JavaScript code. Computed members have values that are computed at run-time and not known at compile-time. No substitution is performed for references to computed members.

An enum member is classified as follows:

  • If the member declaration specifies no value, the member is considered a constant enum member. If the member is the first member in the enum declaration, it is assigned the value zero. Otherwise, it is assigned the value of the immediately preceding member plus one, and an error occurs if the immediately preceding member is not a constant enum member.
  • If the member declaration specifies a value that can be classified as a constant enum expression (as defined below), the member is considered a constant enum member.
  • Otherwise, the member is considered a computed enum member.

Enum value expressions must be of type Any, the Number primitive type, or the enum type itself.

A constant enum expression is a subset of the expression grammar that can be evaluated fully at compile time. An expression is considered a constant enum expression if it is one of the following:

  • A numeric literal.
  • An identifier or property access that denotes a previously declared member in the same constant enum declaration.
  • A parenthesized constant enum expression.
  • A +, –, or ~ unary operator applied to a constant enum expression.
  • A +, –, *, /, %, <<, >>, >>>, &, ^, or | operator applied to two constant enum expressions.

In the example

  1. enum Test {
  2. A,
  3. B,
  4. C = Math.floor(Math.random() * 1000),
  5. D = 10,
  6. E
  7. }

‘A’, ‘B’, ‘D’, and ‘E’ are constant members with values 0, 1, 10, and 11 respectively, and ‘C’ is a computed member.

In the example

  1. enum Style {
  2. None = 0,
  3. Bold = 1,
  4. Italic = 2,
  5. Underline = 4,
  6. Emphasis = Bold | Italic,
  7. Hyperlink = Bold | Underline
  8. }

all members are constant members. Note that enum member declarations can reference other enum members without qualification. Also, because enums are subtypes of the Number primitive type, numeric operators, such as the bitwise OR operator, can be used to compute enum values.