Oh, that’s kind of like a list of numbers, where you can assign every number to a name.
For example, writing an enumeration looks something like this:
(javascript)
enum MyEnum {
// Name, Value (optional)
Dog = 1,
Cat = 2
...
}
This means that for constants, you can replace them with Enums to make them look tidier.
For example, say you want to choose between a direction, ‘left’ or ‘right’.
Now, the initial idea may be to use strings
or numbers.
(left = “left” or 0, and right = “right” or 1)
if (direction == "left") {
...
}
or
if (direction == 0) {
...
}
But instead, you can define enums to make this a lot nicer.
enum Direction {
Left, // enums are incremental, so this will be automatically set to 0
Right // the next member will be +1, so 1
}
if (direction == Direction.Left) {
...
}
It’s also important to mention that members of enumerations are, well - numbers. Each member is assigned a value, which is auto-increment, or you can define values yourself.
enum MyEnum {
Foo, // 0
Bar // 1
}
console.log(MyEnum.Foo); // Expected output: 0
console.log(MyEnum.Bar == 1); // Expected output: true
P.S, all members must adhere to one scheme. If you’re defining a member with an explicit value (eg. Foo = 2
), all other members must have it defined too. You cannot have a mix of implicit and explicit values in you enumerations.
You might also see expressions like Foo = 2 << n;
within enums. These are just powers of 2, so the numbers of the members will be exponential. The <<
operation is a bitwise shift to the left, which means it shifts all of the bits left in a number (eg. 0010 << 1 = 0100)
enum MyEnum {
Foo = 2 << 0, // 2
Bar = 2 << 1, // 4
Baz = 2 << 2 // 8
...
}
With my extension, all of the members are stored in one built-in enumeration, but you can add your own members. I hope this cleared something up, if you have more questions just ask!
Further reading / reference