Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Object-Oriented JavaScript: Part 2

alastair cooper
alastair cooper
30,617 Points

Does JavaScript have an enum keyword?

Thanks Randy for the OOP JavaScript workshop. It was really interesting to see the thought process involved in planning out the objects and the order in which you constructed it.

I have just 1 question. I have been programming with VB for some time now but am relatively new to JavaScript. For all the directions arrays you made, with VB I would have made 1 public enum and tested all the conditions numerically by referencing the 1 list. Does JavaScript have a similar keyword, and if so is there some reason why it was inappropriate in this case?

Thanks

Alastair Cooper

2 Answers

Hi Alastair,

JavaScript does not have an enum keyword like VB, Java, etc.

Luckily, a simple object literal will stand in nicely. I think this is a pretty common pattern:

var status = {
    'SLEEPY' : 0,
    'HUNGRY' : 1
};

function handleStatus(yourStatus) {
    switch (yourStatus) {
        case status.SLEEPY :
            takeNap();
            break;
        case status.HUNGRY :
            eat();
            break;
        default :
            party();
            break;
    }
}
alastair cooper
alastair cooper
30,617 Points

Thank you for that excellent example. I am slowly learning that 'everything is an object' ! I suppose the above example is almost exactly what the VB compiler does under the hood when I declare an enum. Got to think through things more!!

very helpful, thanks.