8

In C# I might use an enumeration.

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

tshepang
  • 11,360
  • 21
  • 88
  • 132
Ben Aston
  • 49,455
  • 61
  • 188
  • 322

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
  • 18,151
  • 10
  • 52
  • 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
  • 69,531
  • 19
  • 142
  • 174
  • 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,326
  • 6
  • 34
  • 38
Jamie Dixon
  • 51,570
  • 19
  • 123
  • 158