Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 27, 2021 10:53 pm GMT

Enums in JavaScript

Prologue

Who I Am?

My name is Marcos Molina a Junior Full-Stack Developer based in Israel.

What I Do?

Sharing knowledge, the purpose of each of my posts is to share a solution to a problem I faced in the industry, side projects, or open-source contributions.

Why?

Because seeing real examples helps me more than the same To-Do List examples.

Content

What Enums are?

A data type that allows us to specify a list of values for a type.
In my side project "Askii" that allows users to answer questions, send it to their friend and see all the answers I used enums for "type" all the possible kinds of questions.
Binary question: Yes or No.
Numeric questions: 1 ,2, etc.
Text questions: Yes, I do love coffee.

What they do?

2)They force you to think about all the possible values that a variable can take.
Once I create an enum on my project, I know that I need to handle three different scenarios in the front-end and in the back-end: binary, numeric, and text questions.

Enums vs list of numbers.

Enums are a constant rather than a list of numbers, increasing the readability of the code.
*This point will be demonstrated in the code example.

When should we use enums?

We should use enums if there are a definite number of fixed values for a variable.

How enums can be implemented?

JavaScript doesn't support enums "built-in", therefore there are some ways to implement them.

Let's build the solution
Note: by convention we use Uppercase letters, written 'binary' but should be 'BINARY'
Alt text of image

Summary

With the solution presented, the power of enums can be achieved as there is in some programming languages. For example TypeScript, Java, and C#.

I hope I could share with you some knowledge.
Did you learn something new ? Let me know in the comments.
Did you love ? Share it with your friends.
Do you know another solution?
Don't be afraid to post your thoughts. I'm here to learn from you.
Networking? LinkedIn

const moodsEnum = Object.freeze({   GOOD : 'GOOD',  AMAZING : 'AMAZING',  SATISFACTORY: 'SATISFACTORY',  ...}

Have an moodsEnum.AMAZING day!


Original Link: https://dev.to/marcosmol204/enums-in-javascript-1274

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To