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

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more