點燈坊

失くすものさえない今が強くなるチャンスよ

Using Object and Symbol to Simulate Enums

Sam Xiao's Avatar 2021-11-26

If we only allow limited values for arguments, using Enums is a good choice. Unfortunately, we don’t have native Enums in JavaScript, but we can use Object and Symbol to simulate it.

Version

ECMAScript 2015

Enums

let Color = Object.freeze ({
  RED: Symbol (),
  GREEN: Symbol (),
  BLUE: Symbol ()
})

let f = color => {
  switch (color) {
    case Color.RED:
      return 'You selected RED'
      break;
    case Color.GREEN:
      return 'You selected GREEN'
      break;
    case Color.BLUE:
      return 'You selected BLUE'
      break;
  }
}

f (Color.RED) // ?

Line 1

let Color = Object.freeze ({
  RED: Symbol (),
  GREEN: Symbol (),
  BLUE: Symbol ()
})
  • Object is similar to Enums, but Object is mutable, and we have to maintain value to be unique
  • Use Object.freeze to make Object immutable
  • Use Symbol to generate unique value

Line 21

f (Color.RED) // ?

It only allows REDGREEN and BLUE as an argument to pass to f; it’s a good chance to pass Enum to f.

Line 7

let f = color => {
  switch (color) {
    case Color.RED:
      return 'You selected RED'
      break;
    case Color.GREEN:
      return 'You selected GREEN'
      break;
    case Color.BLUE:
      return 'You selected BLUE'
      break;
  }
}

We can use Enum to distinguish each value we pass.

enum000

Conclusion

  • Symbol in ES6 facilitates Object to simulate Enums, we don’t have to maintain the unique value of value in Object