Homeconst t="undefined"!=typeof HTMLImageElement&&"loading"in HTMLImageElement.prototype;if(t){co..." />Homeconst t="undefined"!=typeof HTMLImageElement&&"loading"in HTMLImageElement.prototype;if(t){co..." />4 Ways to Create an Enum in JavaScript
Home
Dmitri Pavlutin
I help developers understand Frontend technologies
Post cover

4 Ways to Create an Enum in JavaScript

Posted April 14, 2023

Strings and numbers have an infinite set of values, while others types like booleans are restricted to a finite set.

The days of the week (Monday, Tuesday, ..., Sunday), seasons of the year (winter, spring, summer, autumn), and cardinal directions (north, east, south, west) are examples of sets with finite values.

Using an enum is convenient when a variable has a value from a finite set of predefined constants. The enum saves you from using magic numbers and strings (which is considered an antipattern).

Let's see the 4 good ways to create enums in JavaScript (with their pros and cons).

1. Enum based on a plain object

An enum is a data structure that defines a finite set of named constants. Each constant can be accessed by its name.

Let's consider the sizes of a T-shirt: Small, Medium, and Large.

A simple way (though not the most optimal, see the approaches below) to create an enum in JavaScript is to use a plain JavaScript object.


const Sizes = {
Small: 'small',
Medium: 'medium',
Large: 'large',
}
const mySize = Sizes.Medium
console.log(mySize === Sizes.Medium) // logs true

Sizes is an enum based on a plain JavaScript object which has 3 named constants: Sizes.Small, Sizes.Medium, and Sizes.Large.

Sizes is also a string enum because the values of the named constants are strings: 'small', 'medium', and 'large'.