[Solved-5 Solutions] Enums in javascript - javascript tutorial
Problem:
What is the preferred syntax for defining enums in JavaScript ?
Solution 1:
Define enum like this :
Then you can use this :
If you need enum values to hold properties, you can add them to an extra object:
Then you can like this:
Solution 2:
Here we can define the enum like this:
or
This doesn't prevent you from assigning an undesired value to a variable, which is often the main goal of enums:
let day = DaysEnum.tuesday day = 298832342 // goes through without any errors
Solution 3:
Using Object.defineProperty
able to call and define enum values for any object, without affecting an other attributes.
Attribute writable:false
type is safe. We should able to create a custom object, then call Enum()
on it. The values assigned start at 0 and increment per data.
Solution 4:
Primitive data type which can be used to create an enumeration. It will ensure type safety of the enum as each symbol value is recognized by JavaScript to be unique, i.e. Symbol() != Symbol()
. For example:
Read Also
Java Enum tutorialTo add a description to enum values:
To simplifies this code is required to initialize the enum :
Solution 5:
This solution is implemented by TypeScript interface:
This enables to look up on both MyEnum.Techy
which returns 1, and MyEnum[1]
which returns "Techy" regardless of the order of declaration.