What are Enumerations in JavaScript?

Can anyone please explain to me in simple terms what Enumerations are?

thanks

A way of avoiding magic numbers, basically. Say you have an object that has different behavior depending on whether it’s going left, right, or forward…you could write

objectDirection == 1;
...
if (objectDirection == 0) {
   // do moving-left code here
}
else if (objectDirection == 1) {
   // do moving-right code here
}
else {
   // do forward code here
}

But “0”, “1”, and “2” don’t really tell you anything. They are just magic numbers, and can’t be deciphered just by looking at them. You could use strings – “if (objectDirection == “left”)” – but that takes more memory, is slower, and prone to error: if you used “Left” instead of “left”, the compiler wouldn’t be able to tell you that it’s wrong, and thus your code would run, but it would be buggy.

Instead, you can do

enum Direction {Left, Right, Forward}
...
objectDirection = Direction.Right;
...
if (objectDirection == Direction.Left) {
   // do moving-left code here
}
else if (objectDirection == Direction.Right) {
   // do moving-right code here
}
else {
   // do forward code here
}

Which is a lot more readable and maintainable, and should compile to the same code as the first example (i.e., will be exactly as fast and use the same amount of memory). Not to mention that you are limited to using those items you specify only, which should help prevent bugs…with the first example, you could set objectDirection to any integer, even though you only want 0, 1, or 2, and the compiler won’t care. Also, enums make nice obvious public variable popup-menus–see the axes variable on the MouseLook script on the fp controller in standard assets for an example.

–Eric

Awesome!!

thanks for your insight!!