My name is David Strauß.

I create useful software, write once in a while and run edgy circle.

Cleaner JavaScript code with Enums

There is a very simple and obvious solution for a enum variable type in Javascript, a object. Let’s assume we have three values which represent the state of a client in our fictional chat example.

Not every user can kick others out of the chat, so if a user sends the kick command we have to verify if he is allowed to do so.

if (user.state > 0) {
    // user is allowed to send kick commands
    // process command

Not a very good solution because we place 0s, 1s and 2s in our code which make the code unreadable. So let’s change this, we create a object which contains the different user states and can use this in our code. With this approach we write readable code and if the value of a state changes there is only one place in the code base where we have to change it.

var states = {
    USER: 0,
    MOD: 1,
    ADMIN: 2

if (user.state > states.USER) {
    // user is allowed to send kick commands
    // process command

Do you need help with a messy JavaScript codebase?
You can hire me for JavaScript consulting and development.

Contact me at or +43 664 216 403 4.

« View all posts