Enums

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

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn JavaScript on Codecademy