Enum in JavaScript

Idan Levi
3 min readMar 27, 2020

Enum (Enumerated type) is a special type used to define collections of constants (usually it will be defined by numbers, but not only)

Although javascript doesn’t support enum, still, there are a few ways to implementing it in JavaScript.

Photo by Glenn Carstens-Peters on Unsplash

So why is it so useful?
Much more tidy, readable, understandable to the rest of the team and to you later and convenient for writing (autocomplete by the code editor for example)

I’ll provide examples of a project we were working on

An example of code before we used enums:

if(res.code === 0){
// do something
} else if(res.code === 3 || res.code === 5){
// do something
}

Do you know what 0 or 3 or 5 means? probably not, so you will needs (like me) to ask the programmer the write this code to explain you or read the spec or maybe to be annoying and ask the server-side (in this case)

How we solved this problem in our project?

When we wanted to handle specific insurance types, for data that came from server or activities in client-side, we had a clear division for types of insurance.

5 types of insurance were defined in advance:

  • regular driver
  • New driver
  • Young driver
  • New and young driver
  • A new and young driver with a companion

and from the server, we got numbers from 0 to 4, respectively.

switch (driverInd) { 
case 0:
// do something
break;
case 1:
// do something
break;
....
}

After a week we’ll forget what each number means, right?
and what about a new programmer coming into the project? He/She probably spends an hour facing long specs…
So let’s try enum solution

export const DriverType = { 
REGULAR: 0,
NEW: 1,
YOUNG: 2,
YOUNG_NEW: 3,
YOUNG_NEW_ACCOMPANIED: 4
}

Now we can import the driver types from everywhere and we’ll not need to remember and use the “numbers”
the code much more readable and now it looks like:

switch (driverInd) { 
case DriverType.REGULAR:
// do something
break;
case DriverType.NEW:
// do something
break;
....
}

I want to add a more point, You can change the value (might happen by mistake)

DriverType.YOUNG = 99

To avoid changes it’s possible to seal and freeze the object

export const DriverType = Object.freeze({ 
REGULAR: 0,
NEW: 1,
YOUNG: 2,
YOUNG_NEW: 3,
YOUNG_NEW_ACCOMPANIED: 4
})

Now DriverType can’t change

Who uses PropType:

export const ButtonType = Object.freeze({ 
DEFAULT: 'default',
BIG: 'big',
SMALL: 'small'
})
Bottun.propTypes = { buttonType: PropTypes.oneOf(Object.keys(ButtonType)) })

You obviously noticed that I happened to use strings rather than numbers, this is also possible and will help us avoid errors.

Conclusion

When should you use enums? i recommend each project to create a enums.js file under utils and in every comparison of code and types of numbers or strings, go to the enums file and just add more type, to us, this made a great order in the project code.

--

--