Is it possible to work with Javascript Enumerators?

8

Commonly used in many languages Enumerators make life easier for developers when creating a "list" of constant values within an application. Within Javascript is it possible to use this structure?

    
asked by anonymous 29.09.2017 / 19:35

1 answer

10

Javascript does not have natively enumerators but is something you can implement with relative ease.

Example:

const corSemaforo = {
  VERDE: 0,
  AMARELO: 1,
  VERMELHO: 2
};

let cor = corSemaforo.VERDE;

if (cor == corSemaforo.VERDE) {
  console.log("O semaforo está verde");
}

You can even improve this idea and assign strings to more expressive values instead of numbers.

const corSemaforo = {
  VERDE: "Verde",
  AMARELO: "Amarelo",
  VERMELHO: "Vermelho"
};

So if you write the value of a semaforo somewhere it will have the representation of it in text:

console.log(corSemaforo.VERDE); //Verde

Immutability

Although it has been declared as const only the reference to the object is constant its contents can be modified. This causes the programmer to inadvertently change the enumeration by adding, removing, or changing properties.

See the problem:

const corSemaforo = {
  VERDE: "Verde",
  AMARELO: "Amarelo",
  VERMELHO: "Vermelho"
};

corSemaforo.AZUL = "Azul"; //agora já tem mais uma cor
delete corSemaforo["VERDE"]; //removeu o verde

console.log(corSemaforo); //agora sem VERDE e com AZUL

To avoid this problem we can use freeze of Object that prevents the object from being altered:

const corSemaforo = {
  VERDE: "Verde",
  AMARELO: "Amarelo",
  VERMELHO: "Vermelho"
};

Object.freeze(corSemaforo); //impede futuras alterações

corSemaforo.AZUL = "Azul"; //já não adiciona
delete corSemaforo["VERDE"]; //já não remove

console.log(corSemaforo);
    
29.09.2017 / 20:05