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

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Cloudinary image

Zoom pan, gen fill, restore, overlay, upscale, crop, resize...

Chain advanced transformations through a set of image and video APIs while optimizing assets by 90%.

Explore

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay