Reading the "recommended way" of dealing with ENUM Type in Javascript, I am still uncertain because I can compare the value with a forged value, while I should compare only to a "enum" type value:
var DaysEnum = {"monday":1, "tuesday":2, "wednesday":3, ...}
Object.freeze(DaysEnum)
switch( day ){
case "monday":
return "Hello"
case "tuesday":
return "Hi"
case "blahblahday":
return "No"
}
The strings I made the switch to compare against ("monday", "tuesday", "blahblahday") are totally free from my "enum type: DaysEnum", can be provided by the user and this could lead to some subtle errors not spotted by the interpreter (like typos).
Is there a way to have/lock unique index values of the Enum object?
CA1069: Enums should not have duplicate values.
Can you loop through enum JavaScript? Iterating over the keys Of course, it's also possible to loop over the keys of a string enum, using Object.
The preferred syntax for defining enums in JavaScript is to use the objects see the code below:- var DaysEnum = Object. freeze({"monday":1, "tuesday":2, "wednesday":3, ...})
To convert an enum to an array of objects: Use the Object. keys() method to get an array of the enum's keys. Filter out the unnecessary values for numeric enums.
A possible solution I found with ES2015 could be through Symbols
http://putaindecode.io/en/articles/js/es2015/symbols/
This way you have the unique "locked" values, like you have in other languages, like Java
const DAY_MONDAY = Symbol();
const DAY_TUESDAY = Symbol();
switch(animal) {
case DAY_MONDAY:
return "Hello"
case DAY_TUESDAY:
return "Hi"
//there is no way you can go wrong with DAY_BLAHBLAHDAY
//the compiler will notice it and throw an error
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With