Skip to content

Instantly share code, notes, and snippets.

@PatrickNiyogitare28
Last active May 3, 2021 16:41
Show Gist options
  • Save PatrickNiyogitare28/c85685ce1359d2e25e7ef73dbcf3c3b5 to your computer and use it in GitHub Desktop.
Save PatrickNiyogitare28/c85685ce1359d2e25e7ef73dbcf3c3b5 to your computer and use it in GitHub Desktop.

How to define enums in Javascipt

Enumerations offer an easy way to work with sets of related constants. An enumeration, or Enum , is a symbolic name for a set of values. Enumerations are treated as data types, and you can use them to create sets of constants for use with variables and properties.

Natively javascript doesn't support enums but still you can implement enum in javascipt. One of the available ways is to defining an object and then freezing it after definition. A frozen object can not be modified or you can not add other properties after definition and it's values can not be changed/modified. This keeps the enumeration idea

Syntax to create an enum in javascipt

 const daysEnum = {
      MON:1,
      TUE:2,
      WED:3,
      THUR:4,
      FRI:5,
      SAT:6
      SUN:7
    };
    
 Object.freeze(daysEnum);

How to access values

To be able to access 7 as the seventh day of the week using our difined enum, here is the syntax

let value = daysEnum.SUN;

Hope that was helpful

#javascript #enum

Twitter Badge

@mansurissa
Copy link

Well explained

@mansurissa
Copy link

Well explained

@PatrickNiyogitare28
Copy link
Author

Thank you @mansurissa

@SamuelSabasNayo
Copy link

Nice @patrick!

@PatrickNiyogitare28
Copy link
Author

Yeah @SamuelSabasNayo, thanks

@irumvanselme
Copy link

irumvanselme commented Apr 26, 2021

@PatrickNiyogitare28
Copy link
Author

PatrickNiyogitare28 commented Apr 26, 2021

@felixdusengimana
Copy link

good explanation👍👍

@PatrickNiyogitare28
Copy link
Author

good explanation👍👍

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment