Pseudo Enums in JavaScript || How to Implement a Router in Vue.js

What is the best way to implement an Enum in JavaScript?

That has been the question I asked myself last time I was implementing the router in a Vue.js application. I want so define the routes in a separate file, so that I can reference these everywhere in the application.

The first and obvious idea was to define some consts:

Image for post
Image for post

That means I have to import the specific route name I want to use in a dependend file:

Image for post
Image for post

This looks okay, at first sight, but thinking about it, makes me feel that this solution is not the best way to do so. The cons are:

  • I have to name each constant in the import and
  • it could also clash with other constants.

So I search for something like an Enum to bundle these values together.

I found that the best way to do so is to define an object with all values and freeze it:

Now I can use these Enum with a simple import and will also get no name clashes:

Image for post
Image for post

I could also implement a iterator in this Enum Object or other helper.

Hope this helps a little bit.

Developer since the 80'th, working at Forschungszentrum Jülich (http://www.fz-juelich.de) …

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store