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.
- Value 0: Normal user
- Value 1: Moderator, can kick other users
- Value 2: Administrator, owns the chat
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.
[javascript]if (user.state > 0) { // user is allowed to send kick commands // process command }[/javascript]
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.
[javascript]var states = { USER: 0, MOD: 1, ADMIN: 2 }; if (user.state > states.USER) { // user is allowed to send kick commands // process command } [/javascript]