9

In C# I might use an enumeration.

In JavaScript, how can I limit a value to a set of discrete values idiomatically?

1

3 Answers 3

7

We sometimes define a variable in a JS class 'Enumerations' along these lines:

var Sex = {
    Male: 1,
    Female: 2
};

And then reference it just like a C# enumeration.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. You are capitalizing the object name here because it refers to a constructor function (Object)?
Not particularly, just a hark back to C# and the way we'd use upper case in there.
1

There is no enumeration type in JavaScript. You could, however, wrap an object with a getter and setter method around it like

var value = (function() {
   var val;
   return {
      'setVal': function( v ) {
                   if ( v in [ listOfEnums ] ) {
                       val = v;
                   } else {
                       throw 'value is not in enumeration';
                   }
                },
      'getVal': function() { return val; }
   };
 })();

3 Comments

thanks +1, but if you do something stupid and call it incorrectly value.setVal = 'debug Hell' you end up replacing the function with the string and that's where you are! ...Working now.
Better starting the above with const value = (function... I think.
const wouldnt help you with that. You would need to use something like Object.freeze() if you want to account for this case.
0

Basically, you can't.

Strong typing doesn't exist in JavaScript, so it's not possible to confine your input parameters to a specific type or set of values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.