Is it possible to work with Javascript Enumerators?

Asked

Viewed 179 times

8

Commonly used in several languages Enumerators make life easier for developers when they need to create a "list" of values within an application. Within the Javascript it is possible to use this structure ?

1 answer

10


Javascript does not have native Enumerators but is something that 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");
}

It can even improve this idea and assign strings with more expressive values instead of numbers.

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

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

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

Immutability

Although it was declared const only the reference to the object is constant its contents can be modified. This causes the programmer to inadvertently change the enumerated 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 the function freeze of Object which 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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.