DEV Community

Cover image for Improving your JavaScript with Enums

Improving your JavaScript with Enums

Steve Griffith on August 28, 2022

Enumerations (Enums) are a common data structure feature in many programming languages. While JavaScript does not natively have this feature, we ca...
Collapse
 
fadehelix profile image
Adam Dziendziel •

Thanks for the hint with Object.freeze() when creating enum πŸ’ͺ

Collapse
 
incrementis profile image
Akin C. •

Hi Steve Griffith,

thank you for your article.
I like how you switch from arrays to enums because I think it makes it easier to understand.
I'm not sure if that's intentional, but I also like the touch of humor found in your article.

Overall, I think the article is good enough to fit into an MDN documentation :D.

Collapse
 
prof3ssorst3v3 profile image
Steve Griffith •

That was exactly my intent with the arrays.

Collapse
 
yourmdsarfaraj profile image
MD Sarfaraj •

A well-written explanation. Thank your for sharing !!

Collapse
 
lyavale95 profile image
LyAVALE95 •

Great article thanks

Collapse
 
elijahtrillionz profile image
Elijah Trillionz •

Thanks for the article Griffith.

I needed enums for my library project, your article helped me figure it out. Thanks

Collapse
 
guido_dipilla_39b550ef6d7 profile image
Guido DiPilla •

Thanks for sharing. Most concise and easily understandable explanation I’ve seen…

Collapse
 
decker67 profile image
decker •

I would prefer Errortype.DATA_ERROR.

Collapse
 
prof3ssorst3v3 profile image
Steve Griffith •

:) You can call them whatever you like.
I usually prefer the dot syntax too.
The valuable thing is having strings for names, instead of numbers, plus names and values that cannot be altered.

Collapse
 
decker67 profile image
decker •

You can but you shouldn't, naming counts.

Thread Thread
 
prof3ssorst3v3 profile image
Steve Griffith •

:D
Very true.

Collapse
 
martinszeltins profile image
Neo Hacker •

Why not just use TypeScript which has built-in enums and many more goodies.

Collapse
 
prof3ssorst3v3 profile image
Steve Griffith •

Because a lot more people use JavaScript, not Typescript when developing.
When Typescript compiles back into JS, this is what it is doing.

Collapse
 
majinxin8023 profile image
Mr.ma •

Map δΈι¦™ε—οΌŸ

Collapse
 
prof3ssorst3v3 profile image
Steve Griffith •

Maps have the same problem as objects - they can be altered. Object.freeze( ) gives the best version of an enum.