9

In C# I might use an enumeration.

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

tshepang
  • 12,111
  • 21
  • 91
  • 136
Ben Aston
  • 53,718
  • 65
  • 205
  • 331

3 Answers3

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.

Community
  • 1
  • 1
dougajmcdonald
  • 19,231
  • 12
  • 56
  • 89
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; }
   };
 })();
Sirko
  • 72,589
  • 19
  • 149
  • 183
  • 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. – aamarks Jan 14 '22 at 09:14
  • Better starting the above with `const value = (function...` I think. – aamarks Jan 14 '22 at 09:20
  • 1
    `const` wouldnt help you with that. You would need to use something like [`Object.freeze()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) if you want to account for this case. – Sirko Jan 14 '22 at 10:05
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.

Umber Ferrule
  • 3,358
  • 6
  • 35
  • 38
Jamie Dixon
  • 53,019
  • 19
  • 125
  • 162