Skip to content

Instantly share code, notes, and snippets.

@kevboutin
Last active December 11, 2021 07:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevboutin/fcb76b328b3219131bce3ee291e331d2 to your computer and use it in GitHub Desktop.
Save kevboutin/fcb76b328b3219131bce3ee291e331d2 to your computer and use it in GitHub Desktop.
Best way to do enum in JavaScript
// Season enums can be grouped as static members of a class
class Season {
// Create new instances of the same class as static attributes
static Summer = new Season("summer")
static Autumn = new Season("autumn")
static Winter = new Season("winter")
static Spring = new Season("spring")
constructor(name) {
this.name = name
}
}
// Now we can access enums using namespaced assignments
// this makes it semantically clear that "Summer" is a "Season"
let season = Season.Summer
// We can verify whether a particular variable is a Season enum
console.log(season instanceof Season)
// true
console.log(Symbol('something') instanceof Season)
// false
// We can explicitly check the type based on each enums class
console.log(season.constructor.name)
// 'Season'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment