Deutsche Startseite · English Homepage
STRAVID - Building software collectively.
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 0
s, 1
s and 2
s 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
}
You have questions, ideas or feedback? I like to hear from you and I'm looking forward to exhange thoughts. Please send an email to david@strauss.io and say “Hello”.