Enums

Published Aug 19, 2022
Contribute to Docs

JavaScript has no support for a native enum type, but it is possible to define enums using Objects. In general, enums are a type that can hold a finite number of defined values. The values in enums are not mutable.

Implementing an Enum in JavaScript

A way to implement an enum in JavaScript by creating an Object of key/value pairs and using the Object.freeze() function to make it immutable:

const directions = Object.freeze({
north: 0,
south: 1,
east: 2,
west: 3
});

The enum can be used as follows:

let d = directions.north;

All possible enum values can be listed as follows:

Object.keys(directions).forEach((direction) =>
console.log('direction:', direction)
);

This would produce the output:

direction: north
direction: south
direction: east
direction: west

All contributors

Looking to contribute?

Learn JavaScript on Codecademy