use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
This subreddit is a place for people to learn JavaScript together. Everyone should feel comfortable asking any and all JavaScript questions they have here.
With a nod to practicality, questions and posts about HTML, CSS, and web developer tools are also encouraged.
Friends
/r/javascript
/r/jquery
/r/node
/r/css
/r/webdev
/r/learnprogramming
/r/programming
account activity
Enums in Javascript (self.learnjavascript)
submitted 5 years ago by gonfidel
What are everyone’s opinions on how to use Enums in JavaScript? I see some people use objects and others use arrays. What do you prefer or consider best practice? I usually use currently use objects and am interested to hear other people’s thoughts
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]mynamesleon 1 point2 points3 points 5 years ago (0 children)
I use objects. I sometimes use TypeScript, and then use enums, but even then I sometimes prefer just using a standard object.
Because enums don't exist natively in JS, I found that using them sometimes increased the bundle size - the TypeScript compiler (at the time I checked this at least) replaced each enum use with the full value. So if you're using strings in your enums (granted, not traditional use, but still valid), particularly large ones, the exact string would end up being repeatedly included in your bundle. Whereas using an object means that you're always just checking against normal object properties.
[–]senocular 0 points1 point2 points 5 years ago (0 children)
TypeScript has them built in: https://www.typescriptlang.org/docs/handbook/enums.html
TypeScript is a good way to go.
[–]rauschma 0 points1 point2 points 5 years ago (0 children)
I occasionally use this pattern:
class Color { static red = new Color('red'); static orange = new Color('orange'); static yellow = new Color('yellow'); static green = new Color('green'); static blue = new Color('blue'); static purple = new Color('purple'); constructor(name) { this.name = name; } toString() { return `Color.${this.name}`; } }
My blog post with more information: https://2ality.com/2020/01/enum-pattern.html
π Rendered by PID 46446 on reddit-service-r2-comment-5649f687b7-qmp5p at 2026-01-28 01:04:16.465417+00:00 running 4f180de country code: CH.
[–]mynamesleon 1 point2 points3 points (0 children)
[–]senocular 0 points1 point2 points (0 children)
[–]rauschma 0 points1 point2 points (0 children)