DEV Community

Cover image for This SUPERIOR way ov defining enums in JavaScript!
Calin Baenen
Calin Baenen

Posted on

This SUPERIOR way ov defining enums in JavaScript!

The Standard Way ov Defining An Enum

In JavaScript, the standard way to define an enum – according to the TypeScript compiler – is:

"use strict";
var Fruit;
(function (Fruit) {
  Fruit[Fruit["BANANA"] = 0] = "BANANA";
  Fruit[Fruit["ORANGE"] = 1] = "ORANGE";
  Fruit[Fruit["APPLE"]  = 2] = "APPLE";
})(Fruit || (Fruit = {}));
Enter fullscreen mode Exit fullscreen mode

Or, if we strip the (unnecessary) mapping from number to string, we can do:

"use strict";
var Fruit = {
  "BANANA": 0,
  "ORANGE": 1,
  "APPLE":  2
};
Enter fullscreen mode Exit fullscreen mode

The Better Way ov Defining An Enum

... However, there is a better way to define an enum – and the method will ensure:

  1. the enum values are unique,
  2. the values can't be overriden,
  3. the definition is hoisted.
var Fruit;
{
  Fruit = Object.defineProperties((Fruit = Object.create(null)), {
    BANANA: {writable: false,  value: Symbol("BANANA")},
    ORANGE: {writable: false,  value: Symbol("ORANGE")},
    APPLE:  {writable: false,  value: Symbol("APPLE")}
  });
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Jetbrains Survey

Take part in the Developer Ecosystem Survey!

Share your thoughts and get the chance to win a MacBook Pro, an iPhone 16 Pro, or other exciting prizes. Help shape the coding landscape and earn rewards for your contributions!

Take the survey