Enums have nothing to do with OOP, and JavaScript doesn't have enums. Instead, enums are used whenever there is a choice between a fixed set of values. For example, a boolean is a choice between true and false, which could be implemented as enum Bool { False, True }
. In a GUI library, we might have an enum for alignments: enum HAlignment { LEFT = -1, CENTER = 0, RIGHT = 1 }
.
It is usually irrelevant how the enum is implemented, the important part is that each possible value is distinct. Many languages use integers for enums, though some like Java support arbitrary objects.
Until now, we could just as well have used constants, e.g. const int LEFT = -1, CENTER = 0, RIGHT = 1
. However, a compiler knows that the enum values belong together. So when I switch over the enum values switch(value) {case LEFT: ...; case RIGHT: ...;}
, the compiler can warn me that I have forgotten the CENTER
case. This can be a substantial time saver. In languages without enums or without a switch-case construct, this can be simulated with the Visitor Pattern, though that is more helpful in the presence of static typing.
The other advantage is that enums can be treated as a separate type. E.g. I can declare that a method takes an HAlignment
parameter, rather than any integer. The code will then fail to compile if I provide anything but one of the three possible HAlignment values. However, C's enums aren't well encapsulated and the enum constants can be used interchangeably with integers. Other languages are stricter here.
In JavaScript, we get none of these benefits. The given example declares an object that is treated as an enum. This does have some advantages for the programmer, e.g. it makes documentation easier, groups all the “constants” into a single object, …. However, it is just a convention that such an object is enum-like.
The point here is that HTML only has a finite and known set of tags. You can look at the HTML5 specification and put those element names as an enum into your code, and therefore make it more difficult to sneak a <blink>
tag into your program. It is better to encode this knowledge in one place that to litter your code with special string literals (or worse, magic numbers).
enum People { YOU, NPC, FOO, BAR }
and a function that wants a (People)int
, you can plug whatever, instead of using a number.