Ads by ProfitSence
Close

JavaScript Enum es6

Last Updated on Wednesday 5th Oct 2022

javascript enum es6

TypeScript's enums are a very convenient feature present in many other languages.The easiest way to define an enum would be to use Object.freeze() in combination with a plain object.

			
					const nums = Object.freeze({
  one: 0,
  two: 1,
  three: 2,
  four: 3,
  five: 4,
  six: 5,
  seven: 6
});

			
	

es6 enum

  • An Enum class would only require a constructor with a variable number of arguments.
  • Its job is to add each key to the enum object and freeze the newly created instance.
  • A potential enhancement would be to provide access to the enum values as strings.
  • Using an ES6 symbol is the obvious solution here, as it will not pollute the result of Object.keys() and it will never conflict with any values in the enum.
			
					class Enum {
  constructor(...keys) {
    keys.forEach((key, i) => {
      this[key] = i;
    });
    Object.freeze(this);
  }

  *[Symbol.iterator]() {
    for (let key of Object.keys(this)) yield key;
  }
}

const nums = new Enum(
  'one',
  'two',
  'three',
  'four',
  'five',
  'six',
  'seven'
);

const all = [...nums];

console.log(all);

// [ 'one', 'two', 'three', 'four', 'five', 'six', 'seven' ]

			
	

js enum es6

For example we can give each of the Colors a name and hex value.

			
					/**
 * Enum for common colors.
 * @readonly
 * @enum {{name: string, hex: string}}
 */
const Colors = Object.freeze({
  RED:   { name: "red", hex: "#f00" },
  BLUE:  { name: "blue", hex: "#00f" },
  GREEN: { name: "green", hex: "#0f0" }
});

			
	

References