enum in javascript es6 1

enum in javascript es6

const seasons = {
  SUMMER: {
    BEGINNING: "summer.beginning",
    ENDING: "summer.ending"
  },
  WINTER: "winter",
  SPRING: "spring",
  AUTUMN: "autumn"
};

let season = seasons.SUMMER.BEGINNING;

if (!season) {
  throw new Error("Season is not defined");
}

switch (season) {
  case seasons.SUMMER.BEGINNING:
  // Do something for summer beginning
  case seasons.SUMMER.ENDING:
  // Do something for summer ending
  case seasons.SUMMER:
  // This will work if season = seasons.SUMMER
  // Do something for summer (generic)
  case seasons.WINTER:
  //Do something for winter
  case seasons.SPRING:
  //Do something for spring
  case seasons.AUTUMN:
  //Do something for autumn
}

Here is what the above code is Doing:
1. We’re creating an object called seasons.
2. We’re creating a variable called season and assigning it the value of seasons.SUMMER.BEGINNING.
3. We’re checking if season is defined. If it’s not, we’re throwing an error.
4. We’re using a switch statement to check the value of season.
5. We’re checking if season is equal to seasons.SUMMER.BEGINNING. If it is, we’re doing something.
6. We’re checking if season is equal to seasons.SUMMER.ENDING. If it is, we’re doing something.
7. We’re checking if season is equal to seasons.SUMMER. If it is, we’re doing something.
8. We’re checking if season is equal to seasons.WINTER. If it is, we’re doing something.
9. We’re checking if season is equal to seasons.SPRING. If it is, we’re doing something.
10. We’re checking if season is equal to seasons.AUTUMN. If it is, we’re doing something.

Similar Posts