David Citron David Citron - 1 month ago 7
Javascript Question

Enums in JavaScript?

What is the preferred syntax for defining enums in JavaScript? Something like:

my.namespace.ColorEnum = {
RED : 0,
GREEN : 1,
BLUE : 2
}

// later on

if(currentColor == my.namespace.ColorEnum.RED) {
// whatever
}


Or is there a more preferable idiom?

Answer

This isn't much of an answer, but I'd say that works just fine, personally

Having said that, since it doesn't matter what the values are (you've used 0, 1, 2), I'd use a meaningful string in case you ever wanted to output the current value.